: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
fix(cohorts): repair precalculated cohort data made stale by person merges (#70883)
Gustavo H. Strassburger84e223f4c7b7
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex 93cb35311231..289c42d55901 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -260,10 +260,18 @@ from posthog.models.person_overrides.sql import ()from posthog.models.precalculated_events.sql import (KAFKA_PRECALCULATED_EVENTS_TABLE_SQL,+ PRECALCULATED_EVENTS_DISTRIBUTED_TABLE_SQL,PRECALCULATED_EVENTS_MV_SQL,PRECALCULATED_EVENTS_SHARDED_TABLE_SQL,PRECALCULATED_EVENTS_WRITABLE_TABLE_SQL,)+from posthog.models.precalculated_person_properties.sql import (+ KAFKA_PRECALCULATED_PERSON_PROPERTIES_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_DISTRIBUTED_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_MV_SQL,+ PRECALCULATED_PERSON_PROPERTIES_SHARDED_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_WRITABLE_TABLE_SQL,+)from posthog.models.raw_sessions.sessions_v2 import (DISTRIBUTED_RAW_SESSIONS_TABLE_SQL,RAW_SESSIONS_CREATE_OR_REPLACE_VIEW_SQL,@@ -380,6 +388,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (QUERY_LOG_ARCHIVE_BUFFER_OPS_TABLE_SQL,COHORT_MEMBERSHIP_TABLE_SQL,PRECALCULATED_EVENTS_SHARDED_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_SHARDED_TABLE_SQL,SHARDED_PREAGGREGATION_RESULTS_TABLE_SQL,SHARDED_EXPERIMENT_EXPOSURES_TABLE_SQL,SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE_SQL,@@ -446,7 +455,10 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,DISTRIBUTED_SYSTEM_PROCESSES_TABLE_SQL,COHORT_MEMBERSHIP_WRITABLE_TABLE_SQL,+ PRECALCULATED_EVENTS_DISTRIBUTED_TABLE_SQL,PRECALCULATED_EVENTS_WRITABLE_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_DISTRIBUTED_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_WRITABLE_TABLE_SQL,GROUPS_WRITABLE_TABLE_SQL,PERSONS_WRITABLE_TABLE_SQL,PERSON_DISTINCT_ID2_WRITABLE_TABLE_SQL,@@ -521,6 +533,7 @@ CREATE_KAFKA_TABLE_QUERIES = (KAFKA_SESSION_REPLAY_FEATURES_TABLE_SQL,KAFKA_HEATMAPS_TABLE_SQL,KAFKA_PRECALCULATED_EVENTS_TABLE_SQL,+ KAFKA_PRECALCULATED_PERSON_PROPERTIES_TABLE_SQL,KAFKA_COHORT_MEMBERSHIP_TABLE_SQL,KAFKA_DISTINCT_ID_USAGE_TABLE_SQL,KAFKA_TOPHOG_TABLE_SQL,@@ -560,6 +573,7 @@ CREATE_MV_TABLE_QUERIES = (QUERY_LOG_ARCHIVE_OPS_MV_SQL(view_name=QUERY_LOG_ARCHIVE_OPS_MV, dest_table=WRITABLE_QUERY_LOG_ARCHIVE_TABLE),COHORT_MEMBERSHIP_MV_SQL,PRECALCULATED_EVENTS_MV_SQL,+ PRECALCULATED_PERSON_PROPERTIES_MV_SQL,KAFKA_TO_BUFFER_MV_SQL,*[table.materialized_view_sql for table in EMBEDDING_TABLES],DISTINCT_ID_USAGE_MV_SQL,diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex 82feb014415c..a31163decd51 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -656,6 +656,22 @@'''# ---+# name: test_create_kafka_table_with_different_kafka_host[kafka_precalculated_person_properties]+ '''++ CREATE TABLE IF NOT EXISTS kafka_precalculated_person_properties+ (+ team_id Int64,+ distinct_id String,+ person_id UUID,+ condition String,+ matches Bool,+ source String+ ) ENGINE = Kafka(msk_cluster, kafka_topic_list = 'clickhouse_precalculated_person_properties', kafka_group_name = 'clickhouse_precalculated_person_properties', kafka_format = 'JSONEachRow')+ SETTINGS kafka_max_block_size = 1000000, kafka_poll_max_batch_size = 100000, kafka_poll_timeout_ms = 1000, kafka_flush_interval_ms = 7500, kafka_skip_broken_messages = 100, kafka_num_consumers = 1++ '''+# ---# name: test_create_kafka_table_with_different_kafka_host[kafka_property_values]'''@@ -2774,6 +2790,22 @@'''# ---+# name: test_create_table_query[kafka_precalculated_person_properties]+ '''++ CREATE TABLE IF NOT EXISTS kafka_precalculated_person_properties+ (+ team_id Int64,+ distinct_id String,+ person_id UUID,+ condition String,+ matches Bool,+ source String+ ) ENGINE = Kafka(msk_cluster, kafka_topic_list = 'clickhouse_precalculated_person_properties', kafka_group_name = 'clickhouse_precalculated_person_properties', kafka_format = 'JSONEachRow')+ SETTINGS kafka_max_block_size = 1000000, kafka_poll_max_batch_size = 100000, kafka_poll_timeout_ms = 1000, kafka_flush_interval_ms = 7500, kafka_skip_broken_messages = 100, kafka_num_consumers = 1++ '''+# ---# name: test_create_table_query[kafka_property_values]'''@@ -4675,6 +4707,25 @@'''# ---+# name: test_create_table_query[precalculated_events]+ '''++ CREATE TABLE IF NOT EXISTS precalculated_events+ (+ team_id Int64,+ date Date,+ distinct_id String,+ person_id UUID,+ condition String,+ uuid UUID,+ source String,+ _timestamp DateTime64(6),+ _partition UInt64,+ _offset UInt64+ ) ENGINE = Distributed('posthog', 'posthog_test', 'sharded_precalculated_events', sipHash64(distinct_id))++ '''+# ---# name: test_create_table_query[precalculated_events_mv]'''@@ -4694,6 +4745,40 @@'''# ---+# name: test_create_table_query[precalculated_person_properties]+ '''++ CREATE TABLE IF NOT EXISTS precalculated_person_properties+ (+ team_id Int64,+ distinct_id String,+ person_id UUID,+ condition String,+ matches Bool,+ source String,+ _timestamp DateTime64(6),+ _offset UInt64+ ) ENGINE = Distributed('posthog', 'posthog_test', 'sharded_precalculated_person_properties', sipHash64(distinct_id))++ '''+# ---+# name: test_create_table_query[precalculated_person_properties_mv]+ '''++ CREATE MATERIALIZED VIEW IF NOT EXISTS precalculated_person_properties_mv TO writable_precalculated_person_properties+ AS SELECT+ team_id,+ distinct_id,+ person_id,+ condition,+ matches,+ source,+ _timestamp,+ _offset+ FROM kafka_precalculated_person_properties++ '''+# ---# name: test_create_table_query[property_definitions]'''@@ -7031,6 +7116,24 @@'''# ---+# name: test_create_table_query[sharded_precalculated_person_properties]+ '''++ CREATE TABLE IF NOT EXISTS sharded_precalculated_person_properties+ (+ team_id Int64,+ distinct_id String,+ person_id UUID,+ condition String,+ matches Bool,+ source String,+ _timestamp DateTime64(6),+ _offset UInt64+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.sharded_precalculated_person_properties', '{replica}', _timestamp)+ ORDER BY (team_id, condition, distinct_id)++ '''+# ---# name: test_create_table_query[sharded_query_log_archive]'''CREATE TABLE IF NOT EXISTS sharded_query_log_archive (@@ -9165,6 +9268,23 @@'''# ---+# name: test_create_table_query[writable_precalculated_person_properties]+ '''++ CREATE TABLE IF NOT EXISTS writable_precalculated_person_properties+ (+ team_id Int64,+ distinct_id String,+ person_id UUID,+ condition String,+ matches Bool,+ source String,+ _timestamp DateTime64(6),+ _offset UInt64+ ) ENGINE = Distributed('posthog', 'posthog_test', 'sharded_precalculated_person_properties', sipHash64(distinct_id))++ '''+# ---# name: test_create_table_query[writable_query_log_archive]'''CREATE TABLE IF NOT EXISTS writable_query_log_archive (@@ -11861,6 +11981,24 @@'''# ---+# name: test_create_table_query_replicated_and_storage[sharded_precalculated_person_properties]+ '''++ CREATE TABLE IF NOT EXISTS sharded_precalculated_person_properties+ (+ team_id Int64,+ distinct_id String,+ person_id UUID,+ condition String,+ matches Bool,+ source String,+ _timestamp DateTime64(6),+ _offset UInt64+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.sharded_precalculated_person_properties', '{replica}', _timestamp)+ ORDER BY (team_id, condition, distinct_id)++ '''+# ---# name: test_create_table_query_replicated_and_storage[sharded_query_log_archive]'''CREATE TABLE IF NOT EXISTS sharded_query_log_archive (diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex 4f44d1775c0e..c9e2336c57c5 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -36,7 +36,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.ast import SelectQuery, SelectSetNode, SelectSetQuery-from posthog.hogql.constants import HogQLGlobalSettings, LimitContext+from posthog.hogql.constants import HogQLGlobalSettings, HogQLQuerySettings, LimitContextfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.printer import prepare_and_print_ast@@ -83,6 +83,20 @@ def parse_and_validate_positive_integer(value: Optional[Union[str, int]], value_return parsed_value+def _apply_in_order_aggregation(query: ast.SelectQuery) -> ast.SelectQuery:+ """Set optimize_aggregation_in_order on the inner argMax-dedup subquery.++ The behavioral subqueries fix team_id + condition in WHERE and GROUP BY the trailing+ precalculated_events sort-key columns (date, distinct_id, uuid), so ClickHouse can stream+ the dedup in primary-key order instead of materializing a full hash table over every+ matched event. Mirrors select_from_person_distinct_id_overrides_table.+ """+ inner = query.select_from.table if query.select_from else None+ if isinstance(inner, ast.SelectQuery):+ inner.settings = HogQLQuerySettings(optimize_aggregation_in_order=True)+ return query++def unwrap_cohort(filter: Filter, team_id: int, team: Optional[Team] = None, cohort: Optional[Cohort] = None) -> Filter:"""Flatten cohort-typed properties into nested static/dynamic-cohort PropertyGroups.@@ -1079,15 +1093,28 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):if date_to_datetime:date_filter = "date >= toDate({date_from}) AND date <= toDate({date_to})"- # Build query using precalculated_events+ # Build query using precalculated_events. person_id is resolved with argMax over+ # (distinct_id, date, uuid) rather than read raw: a person merge re-emits the row for+ # the same key with a new person_id, and ReplacingMergeTree only collapses the stale+ # copy on its own schedule, not synchronously with the write. Without this, a merged-away+ # person keeps matching until the background merge happens to run.query_str = f"""SELECT DISTINCTperson_id as id- FROM precalculated_events- WHERE- team_id = {{team_id}}- AND condition = {{condition_hash}}- AND {date_filter}+ FROM+ (+ SELECT+ distinct_id,+ date,+ uuid,+ argMax(person_id, _timestamp) as person_id+ FROM precalculated_events+ WHERE+ team_id = {{team_id}}+ AND condition = {{condition_hash}}+ AND {date_filter}+ GROUP BY date, distinct_id, uuid+ )"""query_params: dict[str, ast.Expr] = {@@ -1098,7 +1125,7 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):if date_to_datetime:query_params["date_to"] = ast.Constant(value=date_to_datetime)- return cast(ast.SelectQuery, parse_select(query_str, query_params))+ return _apply_in_order_aggregation(cast(ast.SelectQuery, parse_select(query_str, query_params)))def get_performed_event_multiple(self, prop: Property) -> ast.SelectQuery:"""@@ -1162,11 +1189,20 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):query_str = f"""SELECTperson_id as id- FROM precalculated_events- WHERE- team_id = {{team_id}}- AND condition = {{condition_hash}}- AND {date_filter}+ FROM+ (+ SELECT+ distinct_id,+ date,+ uuid,+ argMax(person_id, _timestamp) as person_id+ FROM precalculated_events+ WHERE+ team_id = {{team_id}}+ AND condition = {{condition_hash}}+ AND {date_filter}+ GROUP BY date, distinct_id, uuid+ )GROUP BY person_idHAVING count() {sql_operator} {{min_matches}}"""@@ -1180,9 +1216,11 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):if date_to_datetime:query_params["date_to"] = ast.Constant(value=date_to_datetime)- return cast(- ast.SelectQuery,- parse_select(query_str, query_params),+ return _apply_in_order_aggregation(+ cast(+ ast.SelectQuery,+ parse_select(query_str, query_params),+ ))def get_dynamic_cohort_condition(self, prop: Property) -> ast.SelectQuery:diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.pyindex a5e9fda113d2..58782017f11a 100644--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py@@ -30,6 +30,18 @@ CREATE TABLE IF NOT EXISTS precalculated_person_properties () ENGINE = ReplacingMergeTree(_timestamp) ORDER BY (team_id, condition, distinct_id)"""+# Local single-node mirror of the production precalculated_events table. Same sort key and+# ReplacingMergeTree version column so query-time argMax(person_id, _timestamp) dedup behaves+# as it does in production.+_PRECALCULATED_EVENTS_TEST_DDL = """+CREATE TABLE IF NOT EXISTS precalculated_events (+ team_id Int64, date Date, distinct_id String, person_id UUID, condition String,+ uuid UUID, source String, _timestamp DateTime64(6), _partition UInt64, _offset UInt64+) ENGINE = ReplacingMergeTree(_timestamp)+PARTITION BY toYYYYMM(date)+ORDER BY (team_id, condition, date, distinct_id, uuid)+"""+class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):"""Tests for HogQLCohortQuery, particularly the optimization for multiple person property filters."""@@ -2320,6 +2332,103 @@ class TestHogQLRealtimeCohortQuery(ClickhouseTestMixin, APIBaseTest):finally:sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")+ def _seed_precalculated_events(self, rows: list[tuple[UUID, str, str, UUID, dt.date]]) -> None:+ """Seed (person_id, condition, distinct_id, uuid, date) rows; later entries win argMax.++ _timestamp increments per row so query-time argMax(person_id, _timestamp) picks the last+ write for a repeated (condition, date, distinct_id, uuid) key — i.e. the post-merge person.+ """+ base = dt.datetime(2026, 1, 1)+ payload = [+ (+ self.team.pk,+ date,+ distinct_id,+ str(person_id),+ condition,+ str(uuid),+ "test",+ base + dt.timedelta(seconds=offset),+ 0,+ offset,+ )+ for offset, (person_id, condition, distinct_id, uuid, date) in enumerate(rows)+ ]+ sync_execute(+ "INSERT INTO precalculated_events "+ "(team_id, date, distinct_id, person_id, condition, uuid, source, _timestamp, _partition, _offset) VALUES",+ payload,+ )++ def _behavioral_cohort(self, name: str, condition_hash: str, behavioral_value: dict) -> Cohort:+ return Cohort.objects.create(+ team=self.team,+ name=name,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "key": "$pageview",+ "type": "behavioral",+ "negation": False,+ "event_type": "events",+ "time_value": 30,+ "time_interval": "day",+ "conditionHash": condition_hash,+ **behavioral_value,+ }+ ],+ }+ ],+ }+ },+ )++ def test_performed_event_uses_latest_person_id_after_merge(self) -> None:+ """A merge re-emits a precalculated_events row for the same key with the surviving person_id.++ Both behavioral queries resolve person_id via argMax(person_id, _timestamp) so the merged-away+ person stops matching and the survivor matches. Reading person_id raw (the pre-fix behavior)+ would keep the old person until a background ReplacingMergeTree merge — this seeds both rows and+ asserts membership reflects only the survivor, which the string-assertion tests can't catch.+ """+ sync_execute(_PRECALCULATED_EVENTS_TEST_DDL)+ sync_execute("TRUNCATE TABLE precalculated_events")+ try:+ merged_away, survivor = uuid4(), uuid4()+ u1, u2 = uuid4(), uuid4()+ date = dt.date.today()+ # Two events for distinct_id "d1", each first written to merged_away then re-emitted to+ # survivor with a later _timestamp (the reconciliation/merge correction).+ self._seed_precalculated_events(+ [+ (merged_away, "evt_hash", "d1", u1, date),+ (survivor, "evt_hash", "d1", u1, date),+ (merged_away, "evt_hash", "d1", u2, date),+ (survivor, "evt_hash", "d1", u2, date),+ ]+ )++ single = self._behavioral_cohort("evt single", "evt_hash", {"value": "performed_event"})+ single_members = self._realtime_cohort_members(single)+ self.assertIn(str(survivor), single_members)+ self.assertNotIn(str(merged_away), single_members)++ multiple = self._behavioral_cohort(+ "evt multiple",+ "evt_hash",+ {"value": "performed_event_multiple", "operator": "gte", "operator_value": 2},+ )+ multiple_members = self._realtime_cohort_members(multiple)+ self.assertIn(str(survivor), multiple_members)+ self.assertNotIn(str(merged_away), multiple_members)+ finally:+ sync_execute("DROP TABLE IF EXISTS precalculated_events")+def test_nested_boolean_single_scan_membership(self) -> None:"""Execute the nested-boolean single scan and assert membership for `(A AND B) OR (C AND D)`.diff --git a/posthog/management/commands/backfill_precalculated_person_properties.py b/posthog/management/commands/backfill_precalculated_person_properties.pyindex 9564908f2c1b..836eba1789ca 100644--- a/posthog/management/commands/backfill_precalculated_person_properties.py+++ b/posthog/management/commands/backfill_precalculated_person_properties.py@@ -12,7 +12,7 @@ from posthog.temporal.common.client import async_connectfrom posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow import (BackfillPrecalculatedPersonPropertiesCoordinatorInputs,)-from posthog.temporal.messaging.filter_storage import store_filters+from posthog.temporal.messaging.filter_storage import extract_person_property_filters, store_filtersfrom posthog.temporal.messaging.types import PersonPropertyFilterfrom products.cohorts.backend.models.cohort import Cohort, CohortType@@ -20,64 +20,6 @@ from products.cohorts.backend.models.cohort import Cohort, CohortTypelogger = structlog.get_logger(__name__)-def extract_person_property_filters(cohort: Cohort) -> list[PersonPropertyFilter]:- """- Extract person property filters from a realtime cohort.-- Recursively traverses the filter tree to find all person property filters- with conditionHash and bytecode.-- Returns a list of PersonPropertyFilter objects suitable for passing to the workflow.- """- filters: list[PersonPropertyFilter] = []-- if not cohort.filters:- return filters-- properties = cohort.filters.get("properties")- if not properties:- return filters-- def traverse_filter_tree(node):- """Recursively traverse the filter tree to find person property filters."""- if not isinstance(node, dict):- return-- # Check if this is a group node (AND/OR)- node_type = node.get("type")- if node_type in ("AND", "OR"):- # Recursively process children- for child in node.get("values", []):- traverse_filter_tree(child)- return-- # This is a leaf node - check if it's a person property filter- if node_type != "person":- return-- condition_hash = node.get("conditionHash")- bytecode = node.get("bytecode")- property_key = node.get("key")-- # Skip if missing required fields or if they're empty- if not condition_hash or not bytecode or not property_key:- return-- filters.append(- PersonPropertyFilter(- condition_hash=condition_hash,- bytecode=bytecode,- cohort_ids=[], # Will be populated during deduplication- property_key=property_key,- )- )-- # Start traversal from the root properties node- traverse_filter_tree(properties)-- return filters--class Command(BaseCommand):help = "Backfill precalculated_person_properties table for realtime cohorts with person property filters"diff --git a/posthog/settings/schedules.py b/posthog/settings/schedules.pyindex fbd7cab3e87b..53ce6cb86ae1 100644--- a/posthog/settings/schedules.py+++ b/posthog/settings/schedules.py@@ -106,6 +106,19 @@ REALTIME_COHORT_CALCULATION_P99_P100_INTERVAL_MINUTES: int = get_from_env(type_cast=int,)+# How often precalculated_events is reconciled against person_distinct_id_overrides to+# repair rows made stale by person merges. Runs at the realtime calculation cadence so a+# merge is reconciled by the next calculation run; each run is incremental over overrides+# from the last RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS (48 by default), which must stay+# well above this interval and well below the overrides squash cadence+# (SQUASH_PERSON_OVERRIDES_SCHEDULE, weekly by default) — the squash deletes override rows+# after folding them into events, and reconciliation needs to see them before then.+RECONCILE_PRECALCULATED_DATA_INTERVAL_MINUTES: int = get_from_env(+ "RECONCILE_PRECALCULATED_DATA_INTERVAL_MINUTES",+ 15,+ type_cast=int,+)+# Batch delay settings for different percentile rangesREALTIME_COHORT_CALCULATION_P0_P50_BATCH_DELAY_MINUTES: int = get_from_env("REALTIME_COHORT_CALCULATION_P0_P50_BATCH_DELAY_MINUTES",diff --git a/posthog/temporal/messaging/__init__.py b/posthog/temporal/messaging/__init__.pyindex ce160da73ee3..973a86cb40d0 100644--- a/posthog/temporal/messaging/__init__.py+++ b/posthog/temporal/messaging/__init__.py@@ -23,6 +23,13 @@ from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinatorget_query_percentile_thresholds_activity,get_realtime_cohort_selection_activity,)+from posthog.temporal.messaging.reconcile_precalculated_data_workflow import (+ ReconcilePrecalculatedDataWorkflow,+ get_reconciliation_run_config_activity,+ get_reconciliation_team_ids_activity,+ reconcile_team_precalculated_events_activity,+ reconcile_team_precalculated_person_properties_activity,+)WORKFLOWS = [BackfillPrecalculatedEventsWorkflow,@@ -31,6 +38,7 @@ WORKFLOWS = [BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow,RealtimeCohortCalculationWorkflow,RealtimeCohortCalculationCoordinatorWorkflow,+ ReconcilePrecalculatedDataWorkflow,]ACTIVITIES = [backfill_precalculated_events_activity,@@ -40,4 +48,8 @@ ACTIVITIES = [backfill_precalculated_person_properties_activity,get_person_id_ranges_page_activity,process_realtime_cohort_calculation_activity,+ get_reconciliation_team_ids_activity,+ get_reconciliation_run_config_activity,+ reconcile_team_precalculated_events_activity,+ reconcile_team_precalculated_person_properties_activity,]diff --git a/posthog/temporal/messaging/backfill_precalculated_events_workflow.py b/posthog/temporal/messaging/backfill_precalculated_events_workflow.pyindex 898ca4dee665..98ad4e2ba12f 100644--- a/posthog/temporal/messaging/backfill_precalculated_events_workflow.py+++ b/posthog/temporal/messaging/backfill_precalculated_events_workflow.py@@ -54,22 +54,40 @@ async def flush_kafka_batch_async(team_id: int,logger: structlog.BoundLogger,) -> int:- """Flush Kafka messages asynchronously and return count of successful messages."""+ """Flush Kafka messages asynchronously, raising if any failed to deliver.++ flush() blocks until every outstanding delivery callback has fired, so checking+ each result afterwards is non-blocking. Raising lets the Temporal retry policy+ redrive the whole batch instead of silently treating undelivered rows as corrected.+ """if not kafka_results:return 0- successful_count = len(kafka_results)flush_start_time = time.monotonic()await asyncio.to_thread(kafka_producer.flush)flush_duration = time.monotonic() - flush_start_time+ errors = []+ for result in kafka_results:+ try:+ result.get(timeout=0)+ except Exception as e:+ errors.append(str(e))++ successful_count = len(kafka_results) - len(errors)+logger.info(- f"Flushed batch in {flush_duration:.3f}s: {successful_count} messages",+ f"Flushed batch in {flush_duration:.3f}s: {successful_count}/{len(kafka_results)} messages",team_id=team_id,successful_messages=successful_count,flush_duration_seconds=flush_duration,)+ if errors:+ raise RuntimeError(+ f"Kafka delivery failed for {len(errors)}/{len(kafka_results)} messages for team {team_id}: {errors[0]}"+ )+return successful_count@@ -236,21 +254,36 @@ async def backfill_precalculated_events_activity(logger.warning("Invalid BACKFILL_EVENTS_KAFKA_FLUSH_BATCH_SIZE, using default 1000")KAFKA_FLUSH_BATCH_SIZE = 1000+ # events.person_id is the value resolved at ingestion time; if the distinct_id was+ # later re-identified or merged onto another person, only person_distinct_id_overrides+ # knows about it (until the squash job folds overrides back into events). Resolve+ # through the overrides here — mirroring the HogQL events↔overrides lazy join — so+ # backfills write current identity and re-runs repair rows made stale by merges.events_query = """SELECT- uuid,- event,- toDate(timestamp) as date,- distinct_id,- person_id,- properties- FROM events- WHERE team_id = %(team_id)s- AND event IN %(event_names)s- AND timestamp >= %(start_time)s- AND timestamp < %(end_time)s- AND person_id IS NOT NULL- ORDER BY timestamp+ e.uuid AS uuid,+ e.event AS event,+ toDate(e.timestamp) AS date,+ e.distinct_id AS distinct_id,+ if(notEmpty(o.distinct_id), o.person_id, e.person_id) AS person_id,+ e.properties AS properties+ FROM events AS e+ LEFT JOIN (+ SELECT+ distinct_id,+ argMax(person_id, version) AS person_id+ FROM person_distinct_id_overrides+ WHERE team_id = %(team_id)s+ GROUP BY distinct_id+ HAVING argMax(is_deleted, version) = 0+ SETTINGS optimize_aggregation_in_order = 1+ ) AS o ON e.distinct_id = o.distinct_id+ WHERE e.team_id = %(team_id)s+ AND e.event IN %(event_names)s+ AND e.timestamp >= %(start_time)s+ AND e.timestamp < %(end_time)s+ AND e.person_id IS NOT NULL+ ORDER BY e.timestampFORMAT JSONEachRow"""diff --git a/posthog/temporal/messaging/constants.py b/posthog/temporal/messaging/constants.pyindex 9d0baccd0802..1bccf0eefc00 100644--- a/posthog/temporal/messaging/constants.py+++ b/posthog/temporal/messaging/constants.py@@ -10,6 +10,10 @@ REALTIME_COHORT_CALCULATION_SCHEDULE_ID = "realtime-cohort-calculation-schedule"REALTIME_COHORT_CALCULATION_COORDINATOR_WORKFLOW_NAME = "realtime-cohort-calculation-coordinator"CHILD_WORKFLOW_ID_SUFFIX = "child"+# Reconciliation of precalculated_events rows made stale by person merges+RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID = "reconcile-precalculated-data-schedule"+RECONCILE_PRECALCULATED_DATA_WORKFLOW_NAME = "reconcile-precalculated-data"+# Duration percentile-based schedule IDsREALTIME_COHORT_CALCULATION_P0_P50_SCHEDULE_ID = "realtime-cohort-calculation-p0-p50"REALTIME_COHORT_CALCULATION_P50_P80_SCHEDULE_ID = "realtime-cohort-calculation-p50-p80"diff --git a/posthog/temporal/messaging/filter_storage.py b/posthog/temporal/messaging/filter_storage.pyindex 91b604f8d932..b5610a9cb8b7 100644--- a/posthog/temporal/messaging/filter_storage.py+++ b/posthog/temporal/messaging/filter_storage.py@@ -21,6 +21,8 @@ import structlogfrom posthog.redis import get_clientfrom posthog.temporal.messaging.types import BehavioralEventFilter, PersonPropertyFilter+from products.cohorts.backend.models.cohort import Cohort+from common.hogvm.python.operation import HOGQL_BYTECODE_IDENTIFIER, OperationKEY_PREFIX = "backfill_person_properties_filters:"@@ -63,6 +65,44 @@ def combine_filter_bytecodes(filters: list[PersonPropertyFilter]) -> list[Any]:return combined+def extract_person_property_filters(cohort: Cohort) -> list[PersonPropertyFilter]:+ """Extract person-property filters (conditionHash, bytecode, key) from a realtime cohort.++ Recursively traverses the AND/OR filter tree, collecting person leaves that carry a+ conditionHash, bytecode, and key. Leaves missing any of those can't be evaluated later,+ so they're skipped rather than raised on. Shared by the person-properties backfill command+ and the reconciliation workflow so person-filter encoding changes land in one place.+ """+ filters: list[PersonPropertyFilter] = []+ properties = (cohort.filters or {}).get("properties")+ if not properties:+ return filters++ def traverse(node: Any) -> None:+ if not isinstance(node, dict):+ return+ node_type = node.get("type")+ if node_type in ("AND", "OR"):+ for child in node.get("values", []):+ traverse(child)+ return+ if node_type != "person":+ return+ condition_hash = node.get("conditionHash")+ bytecode = node.get("bytecode")+ property_key = node.get("key")+ if not condition_hash or not bytecode or not property_key:+ return+ filters.append(+ PersonPropertyFilter(+ condition_hash=condition_hash, bytecode=bytecode, cohort_ids=[], property_key=property_key+ )+ )++ traverse(properties)+ return filters++def store_filters(filters: list[PersonPropertyFilter], team_id: int, ttl: int = DEFAULT_TTL) -> str:"""Store a list of filters and return a storage key.diff --git a/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py b/posthog/temporal/messaging/reconcile_precalculated_data_workflow.pynew file mode 100644index 000000000000..5d98ff548dca--- /dev/null+++ b/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py@@ -0,0 +1,706 @@+import os+import time+import asyncio+import datetime as dt+import dataclasses+from typing import Any, Optional++import structlog+import temporalio.common+import temporalio.activity+import temporalio.workflow+from structlog.contextvars import bind_contextvars++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.kafka_client.routing import get_producer+from posthog.kafka_client.topics import (+ KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,+ KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,+)+from posthog.sync import database_sync_to_async+from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.clickhouse import get_client+from posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.common.logger import get_logger+from posthog.temporal.messaging.backfill_precalculated_events_workflow import flush_kafka_batch_async+from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (+ evaluate_combined_filters_with_fallback_sync,+ parse_person_properties,+)+from posthog.temporal.messaging.filter_storage import combine_filter_bytecodes, extract_person_property_filters+from posthog.temporal.messaging.types import PersonPropertyFilter++from products.cohorts.backend.models.cohort import Cohort, CohortType++LOGGER = get_logger(__name__)+++def _positive_int_env(name: str, default: int, logger: structlog.BoundLogger) -> int:+ """Parse a positive-int env var, falling back to `default` if unset, malformed, or <= 0.++ A zero/negative batch size breaks range()'s step, and a zero/negative lookback+ places `since` at or after "now", silently excluding every override.+ """+ raw = os.environ.get(name)+ if raw is None:+ return default+ try:+ value = int(raw)+ except ValueError:+ logger.warning(f"Invalid {name}={raw!r}, using default {default}")+ return default+ if value <= 0:+ logger.warning(f"Non-positive {name}={value}, using default {default}")+ return default+ return value+++# precalculated_events stores the person_id that was resolved for a distinct_id when the row+# was written. When a later identify/merge re-points the distinct_id to another person, the+# row silently goes stale: cohort_membership keeps a person the distinct_id no longer belongs+# to and misses the surviving one. The cohort calculation path deliberately never joins+# person tables, so the correction has to happen against the stored rows instead: this+# workflow diffs precalculated_events against person_distinct_id_overrides (the record of+# post-ingestion mapping changes) and re-emits corrected rows through the same Kafka topic+# the realtime consumer and backfill use. ReplacingMergeTree keys the table on+# (team_id, condition, date, distinct_id, uuid) with _timestamp as version, so a re-emitted+# row replaces the stale one. cohort_membership then self-heals on the next calculation run,+# whose FULL OUTER JOIN diff emits 'left' for the old person and 'entered' for the new one.+#+# The override row written at merge time is the invalidation signal: each scheduled run+# picks up distinct_ids whose override landed within the lookback window+# (RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS) and repairs just their rows, so the schedule+# can run at the realtime calculation cadence and a merge is reconciled by the next+# calculation run instead of hours later. A `full_scan` input ignores the window — use it+# for first-deploy remediation or after the workflow was down longer than the lookback.+#+# Timing constraints: the lookback must comfortably exceed the schedule interval (so no+# merge falls between runs), and both must stay well inside the person-overrides squash+# cadence (SQUASH_PERSON_OVERRIDES_SCHEDULE, weekly by default) — the squash folds+# overrides into the events table and then DELETES the override rows, and+# precalculated_events is not part of that squash, so any override this workflow never saw+# becomes unrepairable except by an event backfill re-run.++# Latest surviving mapping per overridden distinct_id; mirrors the HogQL+# person_distinct_id_overrides lazy table (argmax_select with deleted_field="is_deleted").+OVERRIDES_QUERY = """+ SELECT+ distinct_id,+ argMax(person_id, version) AS person_id+ FROM person_distinct_id_overrides+ WHERE team_id = %(team_id)s+ GROUP BY distinct_id+ HAVING argMax(is_deleted, version) = 0+ SETTINGS optimize_aggregation_in_order = 1+ FORMAT JSONEachRow+"""++# Incremental variant: only distinct_ids whose latest override landed inside the lookback+# window. max(_timestamp) (not argMax) so a re-merge of an old distinct_id re-qualifies it.+RECENT_OVERRIDES_QUERY = """+ SELECT+ distinct_id,+ argMax(person_id, version) AS person_id+ FROM person_distinct_id_overrides+ WHERE team_id = %(team_id)s+ GROUP BY distinct_id+ HAVING argMax(is_deleted, version) = 0 AND max(_timestamp) >= toDateTime(%(since)s)+ SETTINGS optimize_aggregation_in_order = 1+ FORMAT JSONEachRow+"""++# Latest version of each precalculated_events row for a batch of overridden distinct_ids.+# GROUP BY covers the full ReplacingMergeTree sort key (minus the constant team_id) with+# argMax by _timestamp, so rows already corrected in an earlier pass — but not yet collapsed+# by a background merge — don't get re-emitted forever.+PRECALCULATED_EVENTS_BATCH_QUERY = """+ SELECT+ condition,+ date,+ distinct_id,+ uuid,+ argMax(person_id, _timestamp) AS person_id,+ argMax(source, _timestamp) AS source+ FROM precalculated_events+ WHERE team_id = %(team_id)s+ AND distinct_id IN %(distinct_ids)s+ GROUP BY condition, date, distinct_id, uuid+ SETTINGS optimize_aggregation_in_order = 1+ FORMAT JSONEachRow+"""++# precalculated_person_properties has the same merge-staleness problem, plus a second layer:+# each row is a verdict (matches true/false) evaluated against the person's properties at+# write time, and a merge changes the surviving person's property set — so re-attributing a+# row isn't enough, its verdict must be re-evaluated. The person-properties backfill can't+# repair these rows either: it stamps distinct_id = person UUID, so its rows never share a+# ReplacingMergeTree key with the realtime consumer's (team_id, condition, distinct_id) rows.+# Cohort membership here is queried by person_id (HogQLRealtimeCohortQuery), not distinct_id,+# so a stale row still tagged with the merged-away person keeps that person showing as a+# member. Since person_id isn't part of the sort key, re-emitting a row for the same+# (team_id, condition, distinct_id) with the surviving person_id overwrites it in place —+# including a matches=false verdict, which is what overwrites a stale matches=true row.++# Existing verdicts for a batch of overridden distinct_ids. Scoped to rows that already+# exist — a condition never evaluated for a distinct_id isn't "stale", it's the backfill's+# job to populate, not this reconciliation's.+EXISTING_PERSON_PROPERTIES_VERDICTS_QUERY = """+ SELECT+ distinct_id,+ condition,+ argMax(matches, (_timestamp, _offset)) AS matches,+ argMax(person_id, (_timestamp, _offset)) AS person_id+ FROM precalculated_person_properties+ WHERE team_id = %(team_id)s+ AND distinct_id IN %(distinct_ids)s+ GROUP BY distinct_id, condition+ FORMAT JSONEachRow+"""++# Current properties for a batch of surviving person_ids, deduped the same way the+# person_distinct_id_overrides queries above are (argMax by version, excluding deleted rows).+PERSON_PROPERTIES_QUERY = """+ SELECT+ id,+ argMax(properties, version) AS properties+ FROM person+ WHERE team_id = %(team_id)s+ AND id IN %(person_ids)s+ GROUP BY id+ HAVING argMax(is_deleted, version) = 0+ SETTINGS optimize_aggregation_in_order = 1+ FORMAT JSONEachRow+"""+++class ReconcilePrecalculatedDataWorkflowInputs:+ """Inputs for the reconciliation workflow."""++ # Manual override for targeted runs; None reconciles every team with realtime cohorts.+ team_ids: Optional[list[int]] = None+ # Ignore the overrides lookback window and diff against every override still in the+ # table. For remediation runs and recovery after downtime longer than the lookback.+ full_scan: bool = False++ @property+ def properties_to_log(self) -> dict[str, Any]:+ return {"team_ids": self.team_ids, "full_scan": self.full_scan}+++class ReconcileTeamInputs:+ """Inputs for reconciling a single team."""++ team_id: int+ full_scan: bool = False+ # Overrides lookback boundary shared by every team in a run; computed once by the+ # workflow so a team queued behind slow/retrying teams doesn't get a narrower window+ # than a team processed immediately (see reconcile_team_precalculated_events_activity).+ since: Optional[dt.datetime] = None++ @property+ def properties_to_log(self) -> dict[str, Any]:+ return {"team_id": self.team_id, "full_scan": self.full_scan}+++class ReconciliationTeamIdsResult:+ """Teams that have realtime cohorts and therefore precalculated_events rows to check."""++ team_ids: list[int]+++class ReconcileTeamResult:+ """Result from reconciling one team's precalculated_events."""++ overridden_distinct_ids: int+ rows_checked: int+ rows_corrected: int+ duration_seconds: float+++class ReconcilePersonPropertiesResult:+ """Result from reconciling one team's precalculated_person_properties."""++ overridden_distinct_ids: int+ verdicts_checked: int+ verdicts_corrected: int+ duration_seconds: float+ # distinct_ids skipped because their surviving person wasn't yet queryable in the+ # persons table (replication lag or a deleted survivor) — retried on a later run.+ distinct_ids_skipped_absent_person: int = 0+ # verdicts left untouched because the condition's bytecode failed to evaluate this+ # run, so we couldn't tell "matches=false" from "couldn't evaluate".+ verdicts_skipped_eval_failed: int = 0+++class ReconciliationRunConfig:+ """Config computed once per workflow run and shared by every team.++ Reading env vars from workflow code would make replay non-deterministic if the value+ changed mid-run, so the workflow fetches both values through this one activity instead+ of reading them directly.+ """++ # Overrides lookback boundary; sharing one value means a team queued behind slow or+ # retrying teams gets the same window as a team processed immediately, instead of a+ # narrower one computed from a later wall-clock time.+ since: dt.datetime+ # Teams are reconciled with this much concurrency so one team's retries can't block+ # every other team in the run for hours.+ team_concurrency: int+++async def get_reconciliation_run_config_activity() -> ReconciliationRunConfig:+ """Compute the run-wide lookback boundary and concurrency once, before any team runs."""+ logger = LOGGER.bind()+ overrides_lookback_hours = _positive_int_env("RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS", 48, logger)+ team_concurrency = _positive_int_env("RECONCILE_PRECALCULATED_DATA_TEAM_CONCURRENCY", 5, logger)+ return ReconciliationRunConfig(+ since=dt.datetime.now(dt.UTC) - dt.timedelta(hours=overrides_lookback_hours),+ team_concurrency=team_concurrency,+ )+++async def get_reconciliation_team_ids_activity() -> ReconciliationTeamIdsResult:+ """Return the teams whose precalculated_events need reconciling.++ Only teams with realtime cohorts feed the realtime calculation path, so only their rows+ can affect cohort_membership.+ """++ @database_sync_to_async+ def get_team_ids() -> list[int]:+ return list(+ Cohort.objects.filter(deleted=False, cohort_type=CohortType.REALTIME)+ .values_list("team_id", flat=True)+ .distinct()+ .order_by("team_id")+ )++ return ReconciliationTeamIdsResult(team_ids=await get_team_ids())+++@database_sync_to_async+def _get_realtime_person_property_filters(team_id: int) -> list[PersonPropertyFilter]:+ """Dedup person-property filters across a team's realtime cohorts, by condition_hash."""+ condition_map: dict[str, PersonPropertyFilter] = {}+ cohorts = Cohort.objects.filter(team_id=team_id, deleted=False, cohort_type=CohortType.REALTIME)+ for cohort in cohorts:+ for extracted in extract_person_property_filters(cohort):+ existing = condition_map.get(extracted.condition_hash)+ if existing is None:+ extracted.cohort_ids = [cohort.id]+ condition_map[extracted.condition_hash] = extracted+ elif cohort.id not in existing.cohort_ids:+ existing.cohort_ids.append(cohort.id)++ return [condition_map[condition_hash] for condition_hash in sorted(condition_map)]+++async def reconcile_team_precalculated_person_properties_activity(+ inputs: ReconcileTeamInputs,+) -> ReconcilePersonPropertiesResult:+ """Re-evaluate precalculated_person_properties verdicts for distinct_ids merged within the window.++ See the module-level comment above EXISTING_PERSON_PROPERTIES_VERDICTS_QUERY for why a+ verdict (not just an attribution) needs re-evaluating, and why matches=false must be+ written explicitly.+ """+ bind_contextvars()+ logger = LOGGER.bind(team_id=inputs.team_id)+ start_time = time.time()++ filters = await _get_realtime_person_property_filters(inputs.team_id)+ if not filters:+ return ReconcilePersonPropertiesResult(+ overridden_distinct_ids=0,+ verdicts_checked=0,+ verdicts_corrected=0,+ duration_seconds=time.time() - start_time,+ )+ combined_bytecode = combine_filter_bytecodes(filters)+ active_condition_hashes = {f.condition_hash for f in filters}++ distinct_id_batch_size = _positive_int_env("RECONCILE_PRECALCULATED_DATA_DISTINCT_ID_BATCH_SIZE", 1000, logger)+ kafka_flush_batch_size = _positive_int_env("RECONCILE_PRECALCULATED_DATA_KAFKA_FLUSH_BATCH_SIZE", 1000, logger)+ overrides_lookback_hours = _positive_int_env("RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS", 48, logger)++ if inputs.full_scan:+ overrides_query = OVERRIDES_QUERY+ overrides_params: dict[str, Any] = {"team_id": inputs.team_id}+ else:+ since = inputs.since or (dt.datetime.now(dt.UTC) - dt.timedelta(hours=overrides_lookback_hours))+ overrides_query = RECENT_OVERRIDES_QUERY+ overrides_params = {"team_id": inputs.team_id, "since": since.strftime("%Y-%m-%d %H:%M:%S")}++ async with Heartbeater(details=(f"Loading person overrides for team {inputs.team_id}",)) as heartbeater:+ with tags_context(+ team_id=inputs.team_id,+ feature=Feature.BEHAVIORAL_COHORTS,+ product=Product.MESSAGING,+ query_type="precalculated_person_properties_reconciliation",+ ):+ async with get_client(team_id=inputs.team_id) as client:+ kafka_producer = get_producer(topic=KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES)+ kafka_results: list = []+ verdicts_checked = 0+ verdicts_corrected = 0+ overridden_distinct_ids = 0+ distinct_ids_skipped_absent_person = 0+ verdicts_skipped_eval_failed = 0++ async def reconcile_batch(batch_overrides: dict[str, str]) -> None:+ nonlocal verdicts_checked, verdicts_corrected+ nonlocal distinct_ids_skipped_absent_person, verdicts_skipped_eval_failed++ existing: dict[tuple[str, str], tuple[bool, str]] = {}+ async for row in client.stream_query_as_jsonl(+ EXISTING_PERSON_PROPERTIES_VERDICTS_QUERY,+ query_parameters={+ "team_id": inputs.team_id,+ "distinct_ids": list(batch_overrides.keys()),+ },+ ):+ existing[(str(row["distinct_id"]), str(row["condition"]))] = (+ bool(row["matches"]),+ str(row["person_id"]),+ )++ if not existing:+ return++ current_person_ids = sorted({batch_overrides[distinct_id] for distinct_id, _ in existing})+ properties_by_person_id: dict[str, dict[str, Any]] = {}+ async for row in client.stream_query_as_jsonl(+ PERSON_PROPERTIES_QUERY,+ query_parameters={"team_id": inputs.team_id, "person_ids": current_person_ids},+ ):+ person_id = str(row["id"])+ properties_by_person_id[person_id] = parse_person_properties(row.get("properties"), person_id)++ # Group by distinct_id so the combined bytecode — which evaluates every+ # filter in one VM pass — runs once per current person, not once per+ # stored verdict. Evaluating it per-verdict would re-derive every other+ # condition's result on each call: O(distinct_ids x filters^2) instead+ # of O(distinct_ids x filters).+ verdicts_by_distinct_id: dict[str, dict[str, tuple[bool, str]]] = {}+ for (distinct_id, condition_hash), verdict in existing.items():+ verdicts_by_distinct_id.setdefault(distinct_id, {})[condition_hash] = verdict++ for distinct_id, condition_verdicts in verdicts_by_distinct_id.items():+ current_person_id = batch_overrides[distinct_id]+ if current_person_id not in properties_by_person_id:+ # The surviving person isn't queryable yet (replication lag after+ # the merge, or a deleted survivor excluded by the query's HAVING).+ # Don't evaluate against empty properties and emit a guessed verdict+ # — that could flip a real matches=true to false and evict a member.+ # The override stays in the lookback window, so a later run retries+ # once the person row lands.+ distinct_ids_skipped_absent_person += 1+ continue+ current_properties = properties_by_person_id[current_person_id]+ hog_globals = {"person": {"properties": current_properties}}+ filter_results = await asyncio.to_thread(+ evaluate_combined_filters_with_fallback_sync,+ combined_bytecode,+ filters,+ hog_globals,+ current_person_id,+ )++ for condition_hash, (stored_matches, stored_person_id) in condition_verdicts.items():+ # A condition_hash absent from filter_results has no fresh verdict+ # to compare against, so leave the stored one untouched rather than+ # overwrite it with a guessed false. Two ways this happens: the+ # condition is no longer one of the team's active realtime filters+ # (stale — the reader already ignores it), or its bytecode failed to+ # evaluate this run (surface that as it can hide a real member).+ if condition_hash not in filter_results:+ if condition_hash in active_condition_hashes:+ verdicts_skipped_eval_failed += 1+ continue+ verdicts_checked += 1+ fresh_matches = bool(filter_results[condition_hash])++ if fresh_matches == stored_matches and current_person_id == stored_person_id:+ continue++ produce_result = await asyncio.to_thread(+ kafka_producer.produce,+ topic=KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,+ data={+ "team_id": inputs.team_id,+ "distinct_id": distinct_id,+ "person_id": current_person_id,+ "condition": condition_hash,+ "matches": fresh_matches,+ "source": f"cohort_filter_{condition_hash}",+ },+ )+ kafka_results.append(produce_result)+ verdicts_corrected += 1++ if len(kafka_results) >= kafka_flush_batch_size:+ await flush_kafka_batch_async(kafka_results, kafka_producer, inputs.team_id, logger)+ kafka_results.clear()++ batch_overrides: dict[str, str] = {}+ async for row in client.stream_query_as_jsonl(overrides_query, query_parameters=overrides_params):+ batch_overrides[str(row["distinct_id"])] = str(row["person_id"])+ overridden_distinct_ids += 1++ if len(batch_overrides) >= distinct_id_batch_size:+ await reconcile_batch(batch_overrides)+ batch_overrides = {}+ heartbeater.details = (+ f"Checked {verdicts_checked} verdicts, corrected {verdicts_corrected} "+ f"({overridden_distinct_ids} distinct_ids so far)",+ )++ if batch_overrides:+ await reconcile_batch(batch_overrides)++ if kafka_results:+ await flush_kafka_batch_async(kafka_results, kafka_producer, inputs.team_id, logger)++ duration_seconds = time.time() - start_time+ logger.info(+ f"Reconciled precalculated_person_properties for team {inputs.team_id}: checked {verdicts_checked} "+ f"verdicts, corrected {verdicts_corrected} in {duration_seconds:.1f}s",+ overridden_distinct_ids=overridden_distinct_ids,+ verdicts_checked=verdicts_checked,+ verdicts_corrected=verdicts_corrected,+ distinct_ids_skipped_absent_person=distinct_ids_skipped_absent_person,+ verdicts_skipped_eval_failed=verdicts_skipped_eval_failed,+ )++ return ReconcilePersonPropertiesResult(+ overridden_distinct_ids=overridden_distinct_ids,+ verdicts_checked=verdicts_checked,+ verdicts_corrected=verdicts_corrected,+ duration_seconds=duration_seconds,+ distinct_ids_skipped_absent_person=distinct_ids_skipped_absent_person,+ verdicts_skipped_eval_failed=verdicts_skipped_eval_failed,+ )+++async def reconcile_team_precalculated_events_activity(inputs: ReconcileTeamInputs) -> ReconcileTeamResult:+ """Re-emit precalculated_events rows whose person_id no longer matches the current mapping."""+ bind_contextvars()+ logger = LOGGER.bind(team_id=inputs.team_id)+ start_time = time.time()++ distinct_id_batch_size = _positive_int_env("RECONCILE_PRECALCULATED_DATA_DISTINCT_ID_BATCH_SIZE", 1000, logger)+ kafka_flush_batch_size = _positive_int_env("RECONCILE_PRECALCULATED_DATA_KAFKA_FLUSH_BATCH_SIZE", 1000, logger)+ overrides_lookback_hours = _positive_int_env("RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS", 48, logger)++ if inputs.full_scan:+ overrides_query = OVERRIDES_QUERY+ overrides_params: dict[str, Any] = {"team_id": inputs.team_id}+ else:+ # The workflow computes and shares one `since` boundary across every team in a run+ # (see ReconcilePrecalculatedDataWorkflow.run); this per-activity fallback only+ # covers direct/manual activity invocations that skip the workflow.+ since = inputs.since or (dt.datetime.now(dt.UTC) - dt.timedelta(hours=overrides_lookback_hours))+ overrides_query = RECENT_OVERRIDES_QUERY+ overrides_params = {"team_id": inputs.team_id, "since": since.strftime("%Y-%m-%d %H:%M:%S")}++ async with Heartbeater(details=(f"Loading person overrides for team {inputs.team_id}",)) as heartbeater:+ with tags_context(+ team_id=inputs.team_id,+ feature=Feature.BEHAVIORAL_COHORTS,+ product=Product.MESSAGING,+ query_type="precalculated_events_reconciliation",+ ):+ async with get_client(team_id=inputs.team_id) as client:+ kafka_producer = get_producer(topic=KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS)+ kafka_results: list = []+ rows_checked = 0+ rows_corrected = 0+ overridden_distinct_ids = 0++ async def reconcile_batch(batch_overrides: dict[str, str]) -> None:+ # Scan this team's precalculated_events for this batch of overridden+ # distinct_ids and re-emit any row still carrying a superseded person_id.+ nonlocal rows_checked, rows_corrected+ async for row in client.stream_query_as_jsonl(+ PRECALCULATED_EVENTS_BATCH_QUERY,+ query_parameters={"team_id": inputs.team_id, "distinct_ids": list(batch_overrides.keys())},+ ):+ rows_checked += 1+ distinct_id = str(row["distinct_id"])+ current_person_id = batch_overrides[distinct_id]+ if str(row["person_id"]) == current_person_id:+ continue++ # Preserve the original source: the backfill coordinator's+ # day-already-backfilled check filters on it, so rewriting it here+ # would make backfilled days look uncovered.+ produce_result = await asyncio.to_thread(+ kafka_producer.produce,+ topic=KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,+ data={+ "uuid": str(row["uuid"]),+ "team_id": inputs.team_id,+ "person_id": current_person_id,+ "distinct_id": distinct_id,+ "condition": str(row["condition"]),+ "date": str(row["date"]),+ "source": str(row["source"]),+ },+ )+ kafka_results.append(produce_result)+ rows_corrected += 1++ if len(kafka_results) >= kafka_flush_batch_size:+ await flush_kafka_batch_async(kafka_results, kafka_producer, inputs.team_id, logger)+ kafka_results.clear()++ # Stream overrides in batches of distinct_id_batch_size and reconcile each+ # batch immediately, rather than materializing every overridden distinct_id+ # for the team before doing any reconciliation. Bounds per-activity memory+ # to O(batch size) regardless of how many distinct_ids a team merged within+ # the lookback window (or, on a full scan, ever).+ batch_overrides: dict[str, str] = {}+ async for row in client.stream_query_as_jsonl(overrides_query, query_parameters=overrides_params):+ batch_overrides[str(row["distinct_id"])] = str(row["person_id"])+ overridden_distinct_ids += 1++ if len(batch_overrides) >= distinct_id_batch_size:+ await reconcile_batch(batch_overrides)+ batch_overrides = {}+ heartbeater.details = (+ f"Checked {rows_checked} rows, corrected {rows_corrected} "+ f"({overridden_distinct_ids} distinct_ids so far)",+ )++ if batch_overrides:+ await reconcile_batch(batch_overrides)++ if not overridden_distinct_ids:+ return ReconcileTeamResult(+ overridden_distinct_ids=0,+ rows_checked=0,+ rows_corrected=0,+ duration_seconds=time.time() - start_time,+ )++ if kafka_results:+ await flush_kafka_batch_async(kafka_results, kafka_producer, inputs.team_id, logger)++ duration_seconds = time.time() - start_time+ logger.info(+ f"Reconciled precalculated_events for team {inputs.team_id}: checked {rows_checked} rows, "+ f"corrected {rows_corrected} in {duration_seconds:.1f}s",+ overridden_distinct_ids=overridden_distinct_ids,+ rows_checked=rows_checked,+ rows_corrected=rows_corrected,+ )++ return ReconcileTeamResult(+ overridden_distinct_ids=overridden_distinct_ids,+ rows_checked=rows_checked,+ rows_corrected=rows_corrected,+ duration_seconds=duration_seconds,+ )++[email protected](name="reconcile-precalculated-data")+class ReconcilePrecalculatedDataWorkflow(PostHogWorkflow):+ """Scheduled workflow that repairs precalculated_events and precalculated_person_properties+ rows made stale by person merges."""++ # Default JSON parse_inputs, so manual runs can pass {"team_ids": [...], "full_scan": true}.+ inputs_cls = ReconcilePrecalculatedDataWorkflowInputs+ inputs_optional = True++ @temporalio.workflow.run+ async def run(self, inputs: ReconcilePrecalculatedDataWorkflowInputs) -> None:+ workflow_logger = temporalio.workflow.logger++ if inputs.team_ids is not None:+ team_ids = inputs.team_ids+ else:+ selection = await temporalio.workflow.execute_activity(+ get_reconciliation_team_ids_activity,+ start_to_close_timeout=dt.timedelta(minutes=2),+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),+ )+ team_ids = selection.team_ids++ if not team_ids:+ workflow_logger.info("No teams with realtime cohorts, nothing to reconcile")+ return++ run_config = await temporalio.workflow.execute_activity(+ get_reconciliation_run_config_activity,+ start_to_close_timeout=dt.timedelta(minutes=1),+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),+ )++ workflow_logger.info(+ f"Reconciling precalculated_events for {len(team_ids)} teams (concurrency={run_config.team_concurrency})"+ )++ activity_retry_policy = temporalio.common.RetryPolicy(+ maximum_attempts=3,+ initial_interval=dt.timedelta(seconds=10),+ maximum_interval=dt.timedelta(minutes=1),+ )++ async def reconcile_team(team_id: int) -> tuple[ReconcileTeamResult, ReconcilePersonPropertiesResult]:+ team_inputs = ReconcileTeamInputs(team_id=team_id, full_scan=inputs.full_scan, since=run_config.since)+ # Sequential, not gathered: both activities touch the same team's ClickHouse data,+ # and keeping them in one place per team keeps a team's failure attributable to a+ # single activity instead of two racing against each other.+ events_result = await temporalio.workflow.execute_activity(+ reconcile_team_precalculated_events_activity,+ team_inputs,+ start_to_close_timeout=dt.timedelta(hours=2),+ heartbeat_timeout=dt.timedelta(minutes=5),+ retry_policy=activity_retry_policy,+ )+ properties_result = await temporalio.workflow.execute_activity(+ reconcile_team_precalculated_person_properties_activity,+ team_inputs,+ start_to_close_timeout=dt.timedelta(hours=2),+ heartbeat_timeout=dt.timedelta(minutes=5),+ retry_policy=activity_retry_policy,+ )+ return events_result, properties_result++ failed_teams: list[int] = []+ total_corrected = 0+ total_verdicts_corrected = 0+ for chunk_start in range(0, len(team_ids), run_config.team_concurrency):+ chunk = team_ids[chunk_start : chunk_start + run_config.team_concurrency]+ # return_exceptions=True: one team's failure shouldn't leave every other team+ # in (or after) its chunk stale.+ chunk_results = await asyncio.gather(+ *(reconcile_team(team_id) for team_id in chunk),+ return_exceptions=True,+ )+ for team_id, result in zip(chunk, chunk_results):+ if isinstance(result, BaseException):+ failed_teams.append(team_id)+ workflow_logger.exception(f"Reconciliation failed for team {team_id}: {result}")+ else:+ events_result, properties_result = result+ total_corrected += events_result.rows_corrected+ total_verdicts_corrected += properties_result.verdicts_corrected++ workflow_logger.info(+ f"Reconciliation completed: corrected {total_corrected} event rows and "+ f"{total_verdicts_corrected} person-property verdicts across "+ f"{len(team_ids) - len(failed_teams)}/{len(team_ids)} teams"+ + (f", failed teams: {failed_teams}" if failed_teams else "")+ )diff --git a/posthog/temporal/messaging/schedule.py b/posthog/temporal/messaging/schedule.pyindex c4cdff8dd1ae..ba37919561e8 100644--- a/posthog/temporal/messaging/schedule.py+++ b/posthog/temporal/messaging/schedule.py@@ -51,10 +51,13 @@ from posthog.temporal.messaging.constants import (REALTIME_COHORT_CALCULATION_P95_P99_SCHEDULE_ID,REALTIME_COHORT_CALCULATION_P99_P100_SCHEDULE_ID,REALTIME_COHORT_CALCULATION_SCHEDULE_ID,+ RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID,+ RECONCILE_PRECALCULATED_DATA_WORKFLOW_NAME,)from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (RealtimeCohortCalculationCoordinatorWorkflowInputs,)+from posthog.temporal.messaging.reconcile_precalculated_data_workflow import ReconcilePrecalculatedDataWorkflowInputs# Default configuration for realtime cohort calculation coordinatorDEFAULT_COORDINATOR_PARALLELISM = 6@@ -204,6 +207,29 @@ async def create_realtime_cohort_calculation_schedule_with_id()+async def create_reconcile_precalculated_data_schedule(client: Client):+ """Create or update the schedule that repairs precalculated_events rows after person merges."""+ from posthog.settings.schedules import RECONCILE_PRECALCULATED_DATA_INTERVAL_MINUTES++ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ RECONCILE_PRECALCULATED_DATA_WORKFLOW_NAME,+ asdict(ReconcilePrecalculatedDataWorkflowInputs()),+ id=RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID,+ task_queue=settings.MESSAGING_TASK_QUEUE,+ ),+ spec=ScheduleSpec(+ intervals=[ScheduleIntervalSpec(every=timedelta(minutes=RECONCILE_PRECALCULATED_DATA_INTERVAL_MINUTES))]+ ),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID):+ await a_update_schedule(client, RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID, schedule, trigger_immediately=False)++async def create_all_realtime_cohort_calculation_schedules(client: Client):"""Create or update all six percentile-based schedules for realtime cohort calculation.diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_events_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_events_workflow.pyindex 13ff91409aae..93d25b1108f4 100644--- a/posthog/temporal/messaging/test/test_backfill_precalculated_events_workflow.py+++ b/posthog/temporal/messaging/test/test_backfill_precalculated_events_workflow.py@@ -1,9 +1,16 @@+import uuid+import datetime as dt+import pytest-from unittest.mock import Mock, patch+from unittest.mock import MagicMock, Mock, patchimport temporalio.exceptions+from confluent_kafka import KafkaExceptionfrom parameterized import parameterized+from temporalio.testing import ActivityEnvironment+from posthog.clickhouse.client import sync_execute+from posthog.models.event.util import create_eventfrom posthog.temporal.messaging.backfill_precalculated_events_workflow import (BackfillPrecalculatedEventsInputs,backfill_precalculated_events_activity,@@ -56,6 +63,25 @@ class TestFlushKafkaBatchAsync:assert result == 2mock_thread.assert_called_once_with(kafka_producer.flush)+ @pytest.mark.asyncio+ async def test_raises_when_a_message_failed_to_deliver(self):+ # A failed delivery must surface as an error, not a silently-inflated success+ # count: the caller relies on this raising to retry the batch instead of treating+ # an undelivered row as corrected.+ kafka_producer = Mock()+ delivered = Mock()+ failed = Mock()+ failed.get.side_effect = KafkaException("broker not available")++ with patch(+ "posthog.temporal.messaging.backfill_precalculated_events_workflow.asyncio.to_thread"+ ) as mock_thread:+ mock_thread.return_value = None+ with pytest.raises(RuntimeError, match="1/2 messages"):+ await flush_kafka_batch_async(+ kafka_results=[delivered, failed], kafka_producer=kafka_producer, team_id=1, logger=Mock()+ )+class TestEvaluateEventCombinedFiltersSync:def test_returns_dict_result(self):@@ -211,6 +237,70 @@ class TestBackfillPrecalculatedEventsActivity:assert result.events_produced == 0+class TestBackfillResolvesMergedPersons:+ async def test_backfill_resolves_person_id_through_overrides(self, team):+ old_person, new_person, plain_person = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()+ timestamp = dt.datetime(2024, 1, 1, 12, 0, tzinfo=dt.UTC)++ # Event ingested while did-merged still resolved to old_person; the distinct_id was+ # later merged onto new_person (recorded in person_distinct_id_overrides).+ merged_event_uuid = uuid.uuid4()+ create_event(merged_event_uuid, "$pageview", team, "did-merged", timestamp, person_id=old_person)+ sync_execute(+ """+ INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version)+ VALUES+ """,+ [(team.pk, "did-merged", str(new_person), 1)],+ )+ # Control: never merged, must keep its ingestion-time person_id.+ plain_event_uuid = uuid.uuid4()+ create_event(plain_event_uuid, "$pageview", team, "did-plain", timestamp, person_id=plain_person)++ match_all_filter = BehavioralEventFilter(+ condition_hash="hash-1",+ bytecode=["_H", 1, Operation.TRUE],+ cohort_ids=[1],+ event_name="$pageview",+ time_value=30,+ time_interval="day",+ )+ inputs = BackfillPrecalculatedEventsInputs(+ team_id=team.pk,+ filter_storage_key="key",+ cohort_ids=[1],+ start_time="2024-01-01 00:00:00",+ end_time="2024-01-02 00:00:00",+ )++ mock_producer = MagicMock()+ with (+ patch(+ "posthog.temporal.messaging.backfill_precalculated_events_workflow.get_event_filters",+ return_value=([match_all_filter], ["$pageview"], {}),+ ),+ patch(+ "posthog.temporal.messaging.backfill_precalculated_events_workflow.get_producer",+ return_value=mock_producer,+ ),+ ):+ result = await ActivityEnvironment().run(backfill_precalculated_events_activity, inputs)++ assert result.events_processed == 2+ assert result.events_produced == 2++ person_id_by_event_uuid = {+ call.kwargs["data"]["uuid"]: call.kwargs["data"]["person_id"]+ for call in mock_producer.produce.call_args_list+ }+ assert person_id_by_event_uuid == {+ str(merged_event_uuid): str(new_person),+ str(plain_event_uuid): str(plain_person),+ }++class TestBackfillPrecalculatedEventsInputs:def test_properties_to_log(self):inputs = BackfillPrecalculatedEventsInputs(diff --git a/posthog/temporal/messaging/test/test_reconcile_precalculated_data_workflow.py b/posthog/temporal/messaging/test/test_reconcile_precalculated_data_workflow.pynew file mode 100644index 000000000000..b63fa3180694--- /dev/null+++ b/posthog/temporal/messaging/test/test_reconcile_precalculated_data_workflow.py@@ -0,0 +1,683 @@+import uuid+import datetime as dt++import pytest+from unittest.mock import MagicMock, patch++from asgiref.sync import sync_to_async+from parameterized import parameterized+from temporalio import activity+from temporalio.testing import ActivityEnvironment, WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.clickhouse.client import sync_execute+from posthog.models.team import Team+from posthog.temporal.messaging.reconcile_precalculated_data_workflow import (+ ReconcilePersonPropertiesResult,+ ReconcilePrecalculatedDataWorkflow,+ ReconcilePrecalculatedDataWorkflowInputs,+ ReconcileTeamInputs,+ ReconcileTeamResult,+ ReconciliationRunConfig,+ ReconciliationTeamIdsResult,+ _get_realtime_person_property_filters,+ _positive_int_env,+ get_reconciliation_run_config_activity,+ get_reconciliation_team_ids_activity,+ reconcile_team_precalculated_events_activity,+ reconcile_team_precalculated_person_properties_activity,+)+from posthog.test.persons import create_person++from products.cohorts.backend.models.cohort import Cohort, CohortType+++def _is_set_bytecode(property_key: str) -> list:+ # person.properties.<key> != NULL — the same is_set bytecode pattern used in+ # test_backfill_precalculated_person_properties_workflow.py's filter-evaluation tests.+ return ["_H", 1, 31, 32, property_key, 32, "properties", 32, "person", 1, 3, 12]+++class TestPositiveIntEnv:+ @parameterized.expand(+ [+ ("valid", "500", 500),+ ("malformed", "not-a-number", 1000),+ ("zero", "0", 1000),+ ("negative", "-5", 1000),+ ]+ )+ def test_parses_or_falls_back_to_default(self, _name, env_value, expected):+ # Guards the reconciliation activity's batch-size/lookback knobs: a zero batch size+ # breaks range()'s step, and a zero/negative lookback silently excludes every override.+ with patch.dict("os.environ", {"RECONCILE_TEST_VAR": env_value}):+ assert _positive_int_env("RECONCILE_TEST_VAR", 1000, MagicMock()) == expected++ def test_unset_uses_default(self, monkeypatch):+ monkeypatch.delenv("RECONCILE_TEST_VAR", raising=False)+ assert _positive_int_env("RECONCILE_TEST_VAR", 1000, MagicMock()) == 1000+++class TestGetReconciliationRunConfigActivity:+ @pytest.mark.asyncio+ async def test_defaults_when_env_unset(self, monkeypatch):+ # The workflow shares this config across every team in a run; a regression here+ # (e.g. reading env vars per-team instead) would silently reopen the queueing bug+ # this activity exists to fix.+ monkeypatch.delenv("RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS", raising=False)+ monkeypatch.delenv("RECONCILE_PRECALCULATED_DATA_TEAM_CONCURRENCY", raising=False)++ before = dt.datetime.now(dt.UTC)+ result = await ActivityEnvironment().run(get_reconciliation_run_config_activity)+ after = dt.datetime.now(dt.UTC)++ assert result.team_concurrency == 5+ assert before - dt.timedelta(hours=48) <= result.since <= after - dt.timedelta(hours=48)+++def _insert_precalculated_event(+ team_id: int,+ distinct_id: str,+ person_id: uuid.UUID,+ condition: str,+ event_uuid: uuid.UUID,+ source: str,+ date: dt.date,+) -> None:+ sync_execute(+ """+ INSERT INTO precalculated_events+ (team_id, date, distinct_id, person_id, condition, uuid, source, _timestamp, _partition, _offset)+ VALUES+ """,+ [+ (+ team_id,+ date,+ distinct_id,+ str(person_id),+ condition,+ str(event_uuid),+ source,+ dt.datetime.now(dt.UTC),+ 0,+ 0,+ )+ ],+ )+++def _insert_override(+ team_id: int,+ distinct_id: str,+ person_id: uuid.UUID,+ version: int = 1,+ timestamp: dt.datetime | None = None,+) -> None:+ # _timestamp has no column default, so it must always be set explicitly: an epoch value+ # would put the override outside the incremental lookback window.+ sync_execute(+ """+ INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version, _timestamp)+ VALUES+ """,+ [(team_id, distinct_id, str(person_id), version, timestamp or dt.datetime.now(dt.UTC))],+ )+++class TestReconcileTeamPrecalculatedEventsActivity:+ async def test_corrects_stale_rows_and_leaves_current_ones_alone(self, team):+ date = dt.date(2024, 1, 1)+ stale_uuid = uuid.uuid4()+ old_person, new_person = uuid.uuid4(), uuid.uuid4()+ synced_person = uuid.uuid4()+ unrelated_person = uuid.uuid4()++ # Stale: distinct_id was re-pointed to new_person after this row was written.+ _insert_precalculated_event(+ team.pk, "did-merged", old_person, "hash-1", stale_uuid, "cohort_event_backfill_hash-1", date+ )+ _insert_override(team.pk, "did-merged", new_person)+ # Already in sync: override agrees with the stored row.+ _insert_precalculated_event(+ team.pk, "did-synced", synced_person, "hash-1", uuid.uuid4(), "cohort_filter_hash-1", date+ )+ _insert_override(team.pk, "did-synced", synced_person)+ # No override at all: must not even be scanned, let alone corrected.+ _insert_precalculated_event(+ team.pk, "did-untouched", unrelated_person, "hash-1", uuid.uuid4(), "cohort_filter_hash-1", date+ )++ mock_producer = MagicMock()+ with patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ):+ result = await ActivityEnvironment().run(+ reconcile_team_precalculated_events_activity, ReconcileTeamInputs(team_id=team.pk)+ )++ assert result.overridden_distinct_ids == 2+ assert result.rows_checked == 2+ assert result.rows_corrected == 1++ produced = [call.kwargs["data"] for call in mock_producer.produce.call_args_list]+ assert produced == [+ {+ "uuid": str(stale_uuid),+ "team_id": team.pk,+ "person_id": str(new_person),+ "distinct_id": "did-merged",+ "condition": "hash-1",+ "date": "2024-01-01",+ # The original source must survive: the backfill coordinator's+ # day-already-backfilled check filters on it.+ "source": "cohort_event_backfill_hash-1",+ }+ ]++ async def test_old_override_needs_full_scan(self, team):+ stale_uuid = uuid.uuid4()+ old_person, new_person = uuid.uuid4(), uuid.uuid4()+ _insert_precalculated_event(+ team.pk, "did-old-merge", old_person, "hash-1", stale_uuid, "cohort_filter_hash-1", dt.date(2024, 1, 1)+ )+ _insert_override(+ team.pk, "did-old-merge", new_person, timestamp=dt.datetime.now(dt.UTC) - dt.timedelta(days=10)+ )++ mock_producer = MagicMock()+ with patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ):+ incremental = await ActivityEnvironment().run(+ reconcile_team_precalculated_events_activity, ReconcileTeamInputs(team_id=team.pk)+ )+ full = await ActivityEnvironment().run(+ reconcile_team_precalculated_events_activity, ReconcileTeamInputs(team_id=team.pk, full_scan=True)+ )++ # Incremental runs only react to overrides inside the lookback window; the full+ # scan is the recovery path for anything older.+ assert incremental.rows_corrected == 0+ assert full.rows_corrected == 1+ assert mock_producer.produce.call_args.kwargs["data"]["person_id"] == str(new_person)++ async def test_deleted_override_does_not_correct(self, team):+ person = uuid.uuid4()+ _insert_precalculated_event(+ team.pk, "did-deleted-override", person, "hash-1", uuid.uuid4(), "cohort_filter_hash-1", dt.date(2024, 1, 1)+ )+ sync_execute(+ """+ INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version, is_deleted, _timestamp)+ VALUES+ """,+ [(team.pk, "did-deleted-override", str(uuid.uuid4()), 2, 1, dt.datetime.now(dt.UTC))],+ )++ mock_producer = MagicMock()+ with patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ):+ result = await ActivityEnvironment().run(+ reconcile_team_precalculated_events_activity, ReconcileTeamInputs(team_id=team.pk)+ )++ assert result.rows_corrected == 0+ mock_producer.produce.assert_not_called()++[email protected]_db(transaction=True)+class TestGetReconciliationTeamIdsActivity:+ async def test_returns_distinct_realtime_cohort_teams_only(self, team):+ other_team = await sync_to_async(Team.objects.create)(+ organization=team.organization, project=team.project, name="other"+ )+ create_cohort = sync_to_async(Cohort.objects.create)+ await create_cohort(team=team, name="rt-1", cohort_type=CohortType.REALTIME)+ await create_cohort(team=team, name="rt-2", cohort_type=CohortType.REALTIME)+ await create_cohort(team=other_team, name="rt-deleted", cohort_type=CohortType.REALTIME, deleted=True)+ await create_cohort(team=other_team, name="batch-only")++ result = await ActivityEnvironment().run(get_reconciliation_team_ids_activity)++ assert result.team_ids == [team.pk]++[email protected]_db(transaction=True)+class TestGetRealtimePersonPropertyFilters:+ async def test_dedupes_condition_shared_across_cohorts(self, team):+ # Two realtime cohorts using the same condition_hash must produce one filter entry+ # (not two) — reconciliation would otherwise evaluate and emit for it twice per batch.+ bytecode = _is_set_bytecode("$browser")+ create_cohort = sync_to_async(Cohort.objects.create)+ cohort_a = await create_cohort(+ team=team,+ name="rt-a",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "person",+ "key": "$browser",+ "conditionHash": "shared-hash",+ "bytecode": bytecode,+ }+ },+ )+ cohort_b = await create_cohort(+ team=team,+ name="rt-b",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "person",+ "key": "$browser",+ "conditionHash": "shared-hash",+ "bytecode": bytecode,+ }+ },+ )++ result = await _get_realtime_person_property_filters(team.pk)++ assert len(result) == 1+ assert result[0].condition_hash == "shared-hash"+ assert sorted(result[0].cohort_ids) == sorted([cohort_a.pk, cohort_b.pk])+++def _insert_person_properties_verdict(+ team_id: int,+ distinct_id: str,+ person_id: uuid.UUID,+ condition: str,+ matches: bool,+ timestamp: dt.datetime | None = None,+) -> None:+ sync_execute(+ """+ INSERT INTO precalculated_person_properties+ (team_id, distinct_id, person_id, condition, matches, source, _timestamp, _offset)+ VALUES+ """,+ [+ (+ team_id,+ distinct_id,+ str(person_id),+ condition,+ matches,+ f"cohort_filter_{condition}",+ timestamp or dt.datetime.now(dt.UTC),+ 0,+ )+ ],+ )++[email protected]_db(transaction=True)+class TestReconcileTeamPrecalculatedPersonPropertiesActivity:+ async def test_corrects_verdict_and_attribution_after_merge(self, team):+ # Old person never had $browser set; the surviving person does. A merge must both+ # re-attribute the row to the surviving person_id and flip the stale matches=False+ # verdict to True — leaving either uncorrected is the bug this activity fixes.+ condition_hash = "browser-set"+ await sync_to_async(Cohort.objects.create)(+ team=team,+ name="rt-browser",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "person",+ "key": "$browser",+ "conditionHash": condition_hash,+ "bytecode": _is_set_bytecode("$browser"),+ }+ },+ )++ old_person = await sync_to_async(create_person)(team=team, distinct_ids=[], properties={})+ new_person = await sync_to_async(create_person)(+ team=team, distinct_ids=["did-merged"], properties={"$browser": "Chrome"}+ )+ _insert_person_properties_verdict(team.pk, "did-merged", old_person.uuid, condition_hash, matches=False)+ _insert_override(team.pk, "did-merged", new_person.uuid)++ mock_producer = MagicMock()+ with patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ):+ result = await ActivityEnvironment().run(+ reconcile_team_precalculated_person_properties_activity, ReconcileTeamInputs(team_id=team.pk)+ )++ assert result.verdicts_checked == 1+ assert result.verdicts_corrected == 1+ produced = [call.kwargs["data"] for call in mock_producer.produce.call_args_list]+ assert produced == [+ {+ "team_id": team.pk,+ "distinct_id": "did-merged",+ "person_id": str(new_person.uuid),+ "condition": condition_hash,+ "matches": True,+ "source": f"cohort_filter_{condition_hash}",+ }+ ]++ async def test_leaves_already_correct_verdict_alone(self, team):+ condition_hash = "browser-set"+ await sync_to_async(Cohort.objects.create)(+ team=team,+ name="rt-browser",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "person",+ "key": "$browser",+ "conditionHash": condition_hash,+ "bytecode": _is_set_bytecode("$browser"),+ }+ },+ )++ person = await sync_to_async(create_person)(+ team=team, distinct_ids=["did-synced"], properties={"$browser": "Chrome"}+ )+ # No merge: override maps the distinct_id to the same person the verdict already has.+ _insert_person_properties_verdict(team.pk, "did-synced", person.uuid, condition_hash, matches=True)+ _insert_override(team.pk, "did-synced", person.uuid)++ mock_producer = MagicMock()+ with patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ):+ result = await ActivityEnvironment().run(+ reconcile_team_precalculated_person_properties_activity, ReconcileTeamInputs(team_id=team.pk)+ )++ assert result.verdicts_checked == 1+ assert result.verdicts_corrected == 0+ mock_producer.produce.assert_not_called()++ async def test_distinct_id_with_no_existing_verdict_is_skipped(self, team):+ # A condition never evaluated for a distinct_id isn't stale — it's the backfill's job+ # to populate, not this reconciliation's. Merely having an override must not conjure+ # a verdict out of nothing.+ condition_hash = "browser-set"+ await sync_to_async(Cohort.objects.create)(+ team=team,+ name="rt-browser",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "person",+ "key": "$browser",+ "conditionHash": condition_hash,+ "bytecode": _is_set_bytecode("$browser"),+ }+ },+ )++ new_person = await sync_to_async(create_person)(+ team=team, distinct_ids=["did-never-evaluated"], properties={"$browser": "Chrome"}+ )+ _insert_override(team.pk, "did-never-evaluated", new_person.uuid)++ mock_producer = MagicMock()+ with patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ):+ result = await ActivityEnvironment().run(+ reconcile_team_precalculated_person_properties_activity, ReconcileTeamInputs(team_id=team.pk)+ )++ assert result.verdicts_checked == 0+ assert result.verdicts_corrected == 0+ mock_producer.produce.assert_not_called()++ async def test_missing_person_is_skipped_not_guessed(self, team):+ # After a merge the surviving person may not be queryable in the persons table yet+ # (replication lag) or be a deleted survivor excluded by the query's HAVING. Evaluating+ # its conditions against empty properties would flip a real matches=True to False and+ # evict the member. The verdict must be left untouched until the person is visible.+ condition_hash = "browser-set"+ await sync_to_async(Cohort.objects.create)(+ team=team,+ name="rt-browser",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "person",+ "key": "$browser",+ "conditionHash": condition_hash,+ "bytecode": _is_set_bytecode("$browser"),+ }+ },+ )++ old_person = await sync_to_async(create_person)(team=team, distinct_ids=[], properties={"$browser": "Chrome"})+ absent_survivor = uuid.uuid4() # never created → not present in the persons table+ _insert_person_properties_verdict(team.pk, "did-merged", old_person.uuid, condition_hash, matches=True)+ _insert_override(team.pk, "did-merged", absent_survivor)++ mock_producer = MagicMock()+ with patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ):+ result = await ActivityEnvironment().run(+ reconcile_team_precalculated_person_properties_activity, ReconcileTeamInputs(team_id=team.pk)+ )++ assert result.distinct_ids_skipped_absent_person == 1+ assert result.verdicts_checked == 0+ assert result.verdicts_corrected == 0+ mock_producer.produce.assert_not_called()++ async def test_eval_failure_leaves_verdict_untouched(self, team):+ # When a condition's bytecode fails to evaluate, its hash is omitted from the evaluator's+ # result. Treating that omission as matches=False would overwrite a real matches=True and+ # permanently evict the member with no self-heal path. The stored verdict must be left alone.+ condition_hash = "browser-set"+ await sync_to_async(Cohort.objects.create)(+ team=team,+ name="rt-browser",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "person",+ "key": "$browser",+ "conditionHash": condition_hash,+ "bytecode": _is_set_bytecode("$browser"),+ }+ },+ )++ old_person = await sync_to_async(create_person)(team=team, distinct_ids=[], properties={"$browser": "Chrome"})+ new_person = await sync_to_async(create_person)(+ team=team, distinct_ids=["did-merged"], properties={"$browser": "Chrome"}+ )+ _insert_person_properties_verdict(team.pk, "did-merged", old_person.uuid, condition_hash, matches=True)+ _insert_override(team.pk, "did-merged", new_person.uuid)++ mock_producer = MagicMock()+ with (+ patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ),+ # Simulate the evaluator omitting the (active) condition because its bytecode threw.+ patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.evaluate_combined_filters_with_fallback_sync",+ return_value={},+ ),+ ):+ result = await ActivityEnvironment().run(+ reconcile_team_precalculated_person_properties_activity, ReconcileTeamInputs(team_id=team.pk)+ )++ assert result.verdicts_skipped_eval_failed == 1+ assert result.verdicts_corrected == 0+ mock_producer.produce.assert_not_called()++ async def test_eval_failure_skips_only_omitted_conditions(self, team):+ # A distinct_id with two stored verdicts where the evaluator returns one hash and omits+ # the other: the returned one must still be corrected while only the omitted one is+ # skipped. Guards against bailing on the whole distinct_id at the first missing hash.+ await sync_to_async(Cohort.objects.create)(+ team=team,+ name="rt-two-conditions",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "person",+ "key": "$browser",+ "conditionHash": "hash-A",+ "bytecode": _is_set_bytecode("$browser"),+ },+ {+ "type": "person",+ "key": "$os",+ "conditionHash": "hash-B",+ "bytecode": _is_set_bytecode("$os"),+ },+ ],+ }+ },+ )++ old_person = await sync_to_async(create_person)(team=team, distinct_ids=[], properties={"$browser": "Chrome"})+ new_person = await sync_to_async(create_person)(+ team=team, distinct_ids=["did-merged"], properties={"$browser": "Chrome"}+ )+ _insert_person_properties_verdict(team.pk, "did-merged", old_person.uuid, "hash-A", matches=True)+ _insert_person_properties_verdict(team.pk, "did-merged", old_person.uuid, "hash-B", matches=True)+ _insert_override(team.pk, "did-merged", new_person.uuid)++ mock_producer = MagicMock()+ with (+ patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.get_producer",+ return_value=mock_producer,+ ),+ # hash-A evaluated (still True); hash-B omitted (bytecode failed this run).+ patch(+ "posthog.temporal.messaging.reconcile_precalculated_data_workflow.evaluate_combined_filters_with_fallback_sync",+ return_value={"hash-A": True},+ ),+ ):+ result = await ActivityEnvironment().run(+ reconcile_team_precalculated_person_properties_activity, ReconcileTeamInputs(team_id=team.pk)+ )++ # hash-A: re-attributed to the surviving person (matches unchanged). hash-B: left alone.+ assert result.verdicts_corrected == 1+ assert result.verdicts_skipped_eval_failed == 1+ produced = [call.kwargs["data"] for call in mock_producer.produce.call_args_list]+ assert produced == [+ {+ "team_id": team.pk,+ "distinct_id": "did-merged",+ "person_id": str(new_person.uuid),+ "condition": "hash-A",+ "matches": True,+ "source": "cohort_filter_hash-A",+ }+ ]+++def _empty_events_result(team_id: int) -> ReconcileTeamResult:+ return ReconcileTeamResult(overridden_distinct_ids=0, rows_checked=0, rows_corrected=0, duration_seconds=0.0)+++def _empty_properties_result() -> ReconcilePersonPropertiesResult:+ return ReconcilePersonPropertiesResult(+ overridden_distinct_ids=0, verdicts_checked=0, verdicts_corrected=0, duration_seconds=0.0+ )+++class TestReconcilePrecalculatedDataWorkflow:+ async def _run(self, team_ids: list[int], events_activity, properties_activity) -> None:+ @activity.defn(name="get_reconciliation_team_ids_activity")+ async def mock_team_ids() -> ReconciliationTeamIdsResult:+ return ReconciliationTeamIdsResult(team_ids=team_ids)++ @activity.defn(name="get_reconciliation_run_config_activity")+ async def mock_run_config() -> ReconciliationRunConfig:+ return ReconciliationRunConfig(since=dt.datetime(2026, 1, 1, tzinfo=dt.UTC), team_concurrency=5)++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[ReconcilePrecalculatedDataWorkflow],+ activities=[mock_team_ids, mock_run_config, events_activity, properties_activity],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(+ ReconcilePrecalculatedDataWorkflow.run,+ ReconcilePrecalculatedDataWorkflowInputs(),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ async def test_run_isolates_failing_team(self):+ # One team's events activity failing must not abort the others: the workflow gathers with+ # return_exceptions=True, so surviving teams still run both activities and the run completes.+ events_calls: list[int] = []+ props_calls: list[int] = []++ @activity.defn(name="reconcile_team_precalculated_events_activity")+ async def events_activity(inputs: ReconcileTeamInputs) -> ReconcileTeamResult:+ events_calls.append(inputs.team_id)+ if inputs.team_id == 102:+ raise RuntimeError("boom")+ return _empty_events_result(inputs.team_id)++ @activity.defn(name="reconcile_team_precalculated_person_properties_activity")+ async def properties_activity(inputs: ReconcileTeamInputs) -> ReconcilePersonPropertiesResult:+ props_calls.append(inputs.team_id)+ return _empty_properties_result()++ await self._run([101, 102, 103], events_activity, properties_activity)++ # Every team's events activity was attempted (the failing one is retried, hence a set).+ assert set(events_calls) == {101, 102, 103}+ # Only the two surviving teams reach the properties activity; the failing team's chain stops.+ assert set(props_calls) == {101, 103}++ async def test_run_no_teams_is_noop(self):+ # Empty team selection short-circuits before any reconcile activity runs.+ events_calls: list[int] = []+ props_calls: list[int] = []++ @activity.defn(name="reconcile_team_precalculated_events_activity")+ async def events_activity(inputs: ReconcileTeamInputs) -> ReconcileTeamResult:+ events_calls.append(inputs.team_id)+ return _empty_events_result(inputs.team_id)++ @activity.defn(name="reconcile_team_precalculated_person_properties_activity")+ async def properties_activity(inputs: ReconcileTeamInputs) -> ReconcilePersonPropertiesResult:+ props_calls.append(inputs.team_id)+ return _empty_properties_result()++ await self._run([], events_activity, properties_activity)++ assert events_calls == []+ assert props_calls == []diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 96ee5838c64f..b48b12dc97c5 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -56,7 +56,10 @@ from posthog.temporal.health_checks.schedule import create_health_check_schedulefrom posthog.temporal.ingestion_acceptance_test.schedule import create_ingestion_acceptance_test_schedulefrom posthog.temporal.logs_alerting.schedule import create_logs_alert_check_schedulefrom posthog.temporal.mcp_analytics.intent_clustering.schedule import create_intent_clustering_coordinator_schedule-from posthog.temporal.messaging.schedule import create_all_realtime_cohort_calculation_schedules+from posthog.temporal.messaging.schedule import (+ create_all_realtime_cohort_calculation_schedules,+ create_reconcile_precalculated_data_schedule,+)from posthog.temporal.product_analytics.upgrade_queries_workflow import UpgradeQueriesWorkflowInputsfrom posthog.temporal.quota_limiting.run_quota_limiting import RunQuotaLimitingInputsfrom posthog.temporal.salesforce_enrichment.conversations_slack_workflow import ConversationsSlackEnrichmentInputs@@ -814,6 +817,7 @@ schedules = [create_experiment_saved_metrics_schedules,create_experiment_precompute_canary_schedule,create_all_realtime_cohort_calculation_schedules,+ create_reconcile_precalculated_data_schedule,create_ingestion_acceptance_test_schedule,create_warehouse_sources_queue_partition_management_schedule,create_health_check_schedules,diff --git a/posthog/test/base.py b/posthog/test/base.pyindex bff985684bba..dfdef2917afa 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -136,15 +136,29 @@ from posthog.models.person.sql import ()from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.precalculated_events.sql import (+ DROP_PRECALCULATED_EVENTS_DISTRIBUTED_TABLE_SQL,DROP_PRECALCULATED_EVENTS_KAFKA_TABLE_SQL,DROP_PRECALCULATED_EVENTS_MV_SQL,DROP_PRECALCULATED_EVENTS_SHARDED_TABLE_SQL,DROP_PRECALCULATED_EVENTS_WRITABLE_TABLE_SQL,KAFKA_PRECALCULATED_EVENTS_TABLE_SQL,+ PRECALCULATED_EVENTS_DISTRIBUTED_TABLE_SQL,PRECALCULATED_EVENTS_MV_SQL,PRECALCULATED_EVENTS_SHARDED_TABLE_SQL,PRECALCULATED_EVENTS_WRITABLE_TABLE_SQL,)+from posthog.models.precalculated_person_properties.sql import (+ DROP_PRECALCULATED_PERSON_PROPERTIES_DISTRIBUTED_TABLE_SQL,+ DROP_PRECALCULATED_PERSON_PROPERTIES_KAFKA_TABLE_SQL,+ DROP_PRECALCULATED_PERSON_PROPERTIES_MV_SQL,+ DROP_PRECALCULATED_PERSON_PROPERTIES_SHARDED_TABLE_SQL,+ DROP_PRECALCULATED_PERSON_PROPERTIES_WRITABLE_TABLE_SQL,+ KAFKA_PRECALCULATED_PERSON_PROPERTIES_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_DISTRIBUTED_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_MV_SQL,+ PRECALCULATED_PERSON_PROPERTIES_SHARDED_TABLE_SQL,+ PRECALCULATED_PERSON_PROPERTIES_WRITABLE_TABLE_SQL,+)from posthog.models.project import Projectfrom posthog.models.raw_sessions.sessions_v2 import (DISTRIBUTED_RAW_SESSIONS_TABLE_SQL,@@ -1945,9 +1959,15 @@ def reset_clickhouse_database() -> None:DROP_COHORT_MEMBERSHIP_KAFKA_TABLE_SQL(),DROP_COHORT_MEMBERSHIP_MV_SQL(),DROP_PRECALCULATED_EVENTS_SHARDED_TABLE_SQL(),+ DROP_PRECALCULATED_EVENTS_DISTRIBUTED_TABLE_SQL(),DROP_PRECALCULATED_EVENTS_WRITABLE_TABLE_SQL(),DROP_PRECALCULATED_EVENTS_KAFKA_TABLE_SQL(),DROP_PRECALCULATED_EVENTS_MV_SQL(),+ DROP_PRECALCULATED_PERSON_PROPERTIES_SHARDED_TABLE_SQL(),+ DROP_PRECALCULATED_PERSON_PROPERTIES_DISTRIBUTED_TABLE_SQL(),+ DROP_PRECALCULATED_PERSON_PROPERTIES_WRITABLE_TABLE_SQL(),+ DROP_PRECALCULATED_PERSON_PROPERTIES_KAFKA_TABLE_SQL(),+ DROP_PRECALCULATED_PERSON_PROPERTIES_MV_SQL(),DROP_PREAGGREGATION_RESULTS_TABLE_SQL(),DROP_SHARDED_PREAGGREGATION_RESULTS_TABLE_SQL(),TRUNCATE_COHORTPEOPLE_TABLE_SQL,@@ -1984,6 +2004,7 @@ def reset_clickhouse_database() -> None:SHARDED_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL(),COHORT_MEMBERSHIP_TABLE_SQL(),PRECALCULATED_EVENTS_SHARDED_TABLE_SQL(),+ PRECALCULATED_PERSON_PROPERTIES_SHARDED_TABLE_SQL(),SHARDED_PREAGGREGATION_RESULTS_TABLE_SQL(),])@@ -2007,8 +2028,12 @@ def reset_clickhouse_database() -> None:WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL(),COHORT_MEMBERSHIP_WRITABLE_TABLE_SQL(),KAFKA_COHORT_MEMBERSHIP_TABLE_SQL(),+ PRECALCULATED_EVENTS_DISTRIBUTED_TABLE_SQL(),PRECALCULATED_EVENTS_WRITABLE_TABLE_SQL(),KAFKA_PRECALCULATED_EVENTS_TABLE_SQL(),+ PRECALCULATED_PERSON_PROPERTIES_DISTRIBUTED_TABLE_SQL(),+ PRECALCULATED_PERSON_PROPERTIES_WRITABLE_TABLE_SQL(),+ KAFKA_PRECALCULATED_PERSON_PROPERTIES_TABLE_SQL(),])run_clickhouse_statement_in_parallel(@@ -2027,6 +2052,7 @@ def reset_clickhouse_database() -> None:WEB_PRE_AGGREGATED_TEAM_SELECTION_DATA_SQL(),COHORT_MEMBERSHIP_MV_SQL(),PRECALCULATED_EVENTS_MV_SQL(),+ PRECALCULATED_PERSON_PROPERTIES_MV_SQL(),QUERY_LOG_ARCHIVE_OPS_MV_SQL(view_name=QUERY_LOG_ARCHIVE_OPS_MV, dest_table=WRITABLE_QUERY_LOG_ARCHIVE_TABLE),