: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
chore(cohorts): delete the legacy precalculated realtime-cohort path (#77485)
Gustavo H. Strassburger853b0362a3ca
diff --git a/.agents/skills/monitoring-ingestion-pipeline/SKILL.md b/.agents/skills/monitoring-ingestion-pipeline/SKILL.mdindex 94517ce6de62..059cce5e0ad4 100644--- a/.agents/skills/monitoring-ingestion-pipeline/SKILL.md+++ b/.agents/skills/monitoring-ingestion-pipeline/SKILL.md@@ -192,7 +192,7 @@ agent pool, KMinion instance, and topic namespace:| `warpstream-logs` | `ingestion-logs`, `clickhouse_logs` | `kminion-warpstream-logs` || `warpstream-traces` | `ingestion-traces`, `clickhouse_traces` | `kminion-warpstream-traces` || `warpstream-shared` | `clickhouse_document_embeddings`, error tracking fingerprint/issue topics, `document_embeddings_input` | `kminion-warpstream-shared` |-| `warpstream-calculated-events` | `clickhouse_precalculated_person_properties`, `clickhouse_prefiltered_events`, `cohort_membership_changed` (US only) | `kminion-warpstream-calculated-events` |+| `warpstream-calculated-events` | `cohort_membership_changed` (US only) | `kminion-warpstream-calculated-events` || `warpstream-cyclotron` | CDP topics (`cdp_cyclotron_hog*`, `cdp_internal_events`, etc.) | `kminion-warpstream-cyclotron` || `warpstream-warehouse-pipelines` | `data_warehouse_source_webhooks`, `data_warehouse_sources_jobs` (US only) | `kminion-warpstream-warehouse-pipelines` |diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.mdindex 83ec242da7ac..cbdb6903b884 100644--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md@@ -127,7 +127,7 @@ Also learned while measuring: ClickHouse 26.x's **query condition cache** makes## 2026-05-28: Dropping `FROM person FINAL` via `argMax` is worse than the original; materialization is the actual win-**Context.** `posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py` builds a raw ClickHouse query that does `SELECT id, JSONExtract(properties, '<key>', 'String'), ... FROM person FINAL WHERE team_id = ... AND id BETWEEN ... AND is_deleted = 0 ORDER BY id FORMAT JSONEachRow`. We flagged the `FINAL` as a smell.+**Context.** A now-deleted precalculated-person-properties backfill workflow built a raw ClickHouse query that did `SELECT id, JSONExtract(properties, '<key>', 'String'), ... FROM person FINAL WHERE team_id = ... AND id BETWEEN ... AND is_deleted = 0 ORDER BY id FORMAT JSONEachRow`. We flagged the `FINAL` as a smell.**Question.** Does dropping `FINAL` via the textbook `argMax(properties, version) GROUP BY id` rewrite actually make the query faster?diff --git a/devenv/intent-map.yaml b/devenv/intent-map.yamlindex d7f8ac8acb5d..e725e7e76304 100644--- a/devenv/intent-map.yaml+++ b/devenv/intent-map.yaml@@ -146,7 +146,7 @@ capabilities:docker_profiles: []nodejs_realtime_cohorts:- description: 'Node.js Realtime Cohorts - precalculated filters and cohort membership'+ description: 'Node.js Realtime Cohorts - cohort membership persistence'requires: [event_ingestion]docker_profiles: []diff --git a/ee/urls.py b/ee/urls.pyindex c61af09cc54b..e095c787d379 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -85,10 +85,6 @@ if settings.ADMIN_PORTAL_ENABLED:except NotRegistered:pass- from posthog.admin.admins.backfill_precalculated_events_admin import backfill_precalculated_events_view- from posthog.admin.admins.backfill_precalculated_person_properties_admin import (- backfill_precalculated_person_properties_view,- )from posthog.admin.admins.code_based_verification_bypass_admin import (CodeBasedVerificationBypassViewSet,CodeBasedVerificationGlobalDisableViewSet,@@ -106,7 +102,6 @@ if settings.ADMIN_PORTAL_ENABLED:notebook_markdown_migration_view,)from posthog.admin.admins.radar_bypass_admin import RadarBypassViewSet, radar_bypass_view- from posthog.admin.admins.realtime_cohort_calculation_admin import analyze_realtime_cohort_calculation_viewfrom posthog.admin.admins.resave_cohorts_admin import resave_cohorts_viewfrom posthog.admin.admins.tophog_admin import tophog_dashboard_view, tophog_restrictions_view@@ -119,11 +114,6 @@ if settings.ADMIN_PORTAL_ENABLED:path("admin/redisvalues", redis_values_view, name="redis_values"),path("admin/redis/edit-ttl", redis_edit_ttl_view, name="redis_edit_ttl"),path("admin/apikeysearch", api_key_search_view, name="api_key_search"),- path(- "admin/realtime-cohorts-calculation/",- admin.site.admin_view(analyze_realtime_cohort_calculation_view),- name="realtime-cohorts-calculation",- ),path("admin/radar-bypass/",admin.site.admin_view(radar_bypass_view),@@ -164,16 +154,6 @@ if settings.ADMIN_PORTAL_ENABLED:admin.site.admin_view(resave_cohorts_view),name="resave-cohorts",),- path(- "admin/backfill-precalculated-events/",- admin.site.admin_view(backfill_precalculated_events_view),- name="backfill-precalculated-events",- ),- path(- "admin/backfill-precalculated-person-properties/",- admin.site.admin_view(backfill_precalculated_person_properties_view),- name="backfill-precalculated-person-properties",- ),path("admin/distinct-id-usage/",admin.site.admin_view(distinct_id_usage_view),diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex deca0e1ef3e1..439eb3b1b410 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -32,9 +32,8 @@ export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {cdpHogflowSubscriptionMatcher: isDevEnv(),}-/** Realtime Cohorts - precalculated filters and cohort membership */+/** Realtime Cohorts - cohort membership persistence */export const CAPABILITIES_REALTIME_COHORTS: PluginServerCapabilities = {- cdpPrecalculatedFilters: true,cdpCohortMembership: true,}@@ -141,9 +140,9 @@ export function getPluginServerCapabilities(cdpCyclotronWorkerEmailLegacyPg: true,}case PluginServerMode.cdp_precalculated_filters:- return {- cdpPrecalculatedFilters: true,- }+ // The consumer is gone. Boot with no capabilities so a pod that charts still+ // launches in this mode idles instead of crash-looping on an unknown mode.+ return {}case PluginServerMode.cdp_hogflow_subscription_matcher:return {cdpHogflowSubscriptionMatcher: true,diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 9d6e31cdd9e0..5b4cbf66da25 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -11,11 +11,7 @@ import { TeamManager } from '~/common/utils/team-manager'import type { CommonConfig } from '../common/config'import { InternalCaptureService } from '../common/services/internal-capture'import type { CdpConfig } from './config'-import {- PrecalculatedPersonPropertiesOutput,- PrefilteredEventsOutput,- WarehouseSourceWebhooksOutput,-} from './outputs/outputs'+import { WarehouseSourceWebhooksOutput } from './outputs/outputs'import { CdpProducerName } from './outputs/producers'import { createCdpOutputsRegistry } from './outputs/registry'import { CapturedEventsService } from './services/captured-events/captured-events.service'@@ -50,13 +46,7 @@ import { MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from './utils/cdp-fetch'import { EncryptedFields } from './utils/encryption-utils'/** Union of every output name resolved by `createCdpOutputsRegistry()`. */-export type CdpOutput =- | AppMetricsOutput- | LogEntriesOutput- | HogInvocationResultsOutput- | PrefilteredEventsOutput- | PrecalculatedPersonPropertiesOutput- | WarehouseSourceWebhooksOutput+export type CdpOutput = AppMetricsOutput | LogEntriesOutput | HogInvocationResultsOutput | WarehouseSourceWebhooksOutputexport type CdpOutputs = IngestionOutputs<CdpOutput>@@ -163,10 +153,6 @@ export type CdpCoreServicesConfig = Pick<| 'HOG_INVOCATION_RESULTS_ENABLED'| 'MESSAGE_ASSETS_TOPIC'| 'MESSAGE_ASSETS_PRODUCER'- | 'CDP_PREFILTERED_EVENTS_TOPIC'- | 'CDP_PREFILTERED_EVENTS_PRODUCER'- | 'CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC'- | 'CDP_PRECALCULATED_PERSON_PROPERTIES_PRODUCER'| 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC'| 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER'>diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex a0a1a659d1d0..b7eca1915f64 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -1,7 +1,5 @@import {KAFKA_APP_METRICS_2,- KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,- KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,KAFKA_EVENTS_JSON,KAFKA_HOG_INVOCATION_RESULTS,KAFKA_LOG_ENTRIES,@@ -14,7 +12,6 @@ import { ClickhouseConfig, getDefaultClickhouseConfig } from '../common/clickhouimport {CdpProducerName,WAREHOUSE_PRODUCER,- WARPSTREAM_CALCULATED_EVENTS_PRODUCER,WARPSTREAM_CYCLOTRON_PRODUCER,WARPSTREAM_INGESTION_PRODUCER,} from './outputs/producers'@@ -112,10 +109,6 @@ export type CdpConfig = ClickhouseConfig & {// How many rerun wrapper jobs the worker dequeues per cyclotron-v2 poll.// Kept small by default — each job runs a full ClickHouse query per page.CDP_RERUN_WORKER_BATCH_SIZE: number- CDP_PREFILTERED_EVENTS_TOPIC: string- CDP_PREFILTERED_EVENTS_PRODUCER: CdpProducerName- CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC: string- CDP_PRECALCULATED_PERSON_PROPERTIES_PRODUCER: CdpProducerNameCDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC: stringCDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER: CdpProducerName@@ -282,10 +275,6 @@ export function getDefaultCdpConfig(): CdpConfig {// Small by default — rerun jobs are heavy (a full ClickHouse query per// page), so a replica drains one wrapper job at a time unless tuned up.CDP_RERUN_WORKER_BATCH_SIZE: 1,- CDP_PREFILTERED_EVENTS_TOPIC: KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,- CDP_PREFILTERED_EVENTS_PRODUCER: WARPSTREAM_CALCULATED_EVENTS_PRODUCER,- CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC: KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,- CDP_PRECALCULATED_PERSON_PROPERTIES_PRODUCER: WARPSTREAM_CALCULATED_EVENTS_PRODUCER,CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC: KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER: WAREHOUSE_PRODUCER,diff --git a/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.test.tsdeleted file mode 100644index 8a5ab659f61a..000000000000--- a/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.test.ts+++ /dev/null@@ -1,699 +0,0 @@-import { mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'--import { KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS } from '~/common/config/kafka-topics'-import { closeHub, createHub } from '~/common/utils/db/hub'-import { resetKafka } from '~/tests/helpers/kafka'--import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'-import { buildInlineFiltersForCohorts, createCohort, getFirstTeam, resetTestDatabase } from '../../../tests/helpers/sql'-import { Hub, RawClickHouseEvent, Team } from '../../types'-import { CdpPrecalculatedFiltersConsumer } from './cdp-precalculated-filters.consumer'--jest.setTimeout(20_000)--const TEST_FILTERS = {- // Simple pageview event filter: event == '$pageview'- pageview: ['_H', 1, 32, '$pageview', 32, 'event', 1, 1, 11],-- // Chrome browser AND pageview event filter: properties.$browser == 'Chrome' AND event == '$pageview'- chromePageview: [- '_H',- 1,- 32,- 'Chrome',- 32,- '$browser',- 32,- 'properties',- 1,- 2,- 11,- 32,- '$pageview',- 32,- 'event',- 1,- 1,- 11,- 3,- 2,- 4,- 1,- ],-- // Complex filter: pageview event AND (Chrome browser contains match OR has IP property)- complexChromeWithIp: [- '_H',- 1,- 32,- '$pageview',- 32,- 'event',- 1,- 1,- 11,- 32,- '%Chrome%',- 32,- '$browser',- 32,- 'properties',- 1,- 2,- 2,- 'toString',- 1,- 18,- 3,- 2,- 32,- '$pageview',- 32,- 'event',- 1,- 1,- 11,- 31,- 32,- '$ip',- 32,- 'properties',- 1,- 2,- 12,- 3,- 2,- 4,- 2,- ],-- // Billing product activated filter- billingProductActivated: [- '_H',- 1,- 32,- 'billing product activated',- 32,- 'event',- 1,- 1,- 11,- 32,- 'platform_and_support',- 32,- 'product_key',- 32,- 'properties',- 1,- 2,- 11,- 32,- 'teams-20240208',- 32,- 'plans__platform_and_support',- 32,- 'properties',- 1,- 2,- 11,- 3,- 2,- 3,- 2,- ],-- // Product unsubscribed filter- productUnsubscribed: [- '_H',- 1,- 32,- 'product unsubscribed',- 32,- 'event',- 1,- 1,- 11,- 32,- 'platform_and_support',- 32,- 'product',- 32,- 'properties',- 1,- 2,- 11,- 3,- 2,- ],-- // Person property is_organization_first_user filter- isOrgFirstUser: ['_H', 1, 29, 32, 'is_organization_first_user', 32, 'properties', 32, 'person', 1, 3, 11],-}--describe('CdpPrecalculatedFiltersConsumer', () => {- let processor: CdpPrecalculatedFiltersConsumer- let hub: Hub- let team: Team-- beforeEach(async () => {- await resetKafka()- await resetTestDatabase()-- mockProducerObserver.resetKafkaProducer()- hub = await createHub()- team = await getFirstTeam(hub.postgres)-- processor = new CdpPrecalculatedFiltersConsumer(hub, createCdpConsumerDeps(hub))- await processor.start()- })-- afterEach(async () => {- await processor.stop()- await closeHub(hub)- jest.restoreAllMocks()- })-- describe('cohort filter matching and Kafka publishing', () => {- it('should publish pre-calculated events to Kafka when cohort filter matches', async () => {- // Create a cohort with complex behavioral filter: pageview with browser event filter- const conditionHash = 'test_hash_001'- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: '$pageview',- type: 'behavioral',- value: 'performed_event_multiple',- bytecode: TEST_FILTERS.chromePageview,- negation: false,- operator: 'gte',- event_type: 'events',- conditionHash: conditionHash,- event_filters: [- { key: '$browser', type: 'event', value: 'Chrome', operator: 'exact' },- ],- operator_value: 5,- explicit_datetime: '-30d',- },- ],- },- ],- },- })- await createCohort(hub.postgres, team.id, 'Test cohort', filters)-- // Create a matching event- const personId = '550e8400-e29b-41d4-a716-446655440000'- const distinctId = 'test-distinct-123'- const eventUuid = 'test-uuid-1'- const timestamp = '2025-03-03T10:15:46.319000-08:00'-- const messages = [- {- value: Buffer.from(- JSON.stringify({- team_id: team.id,- event: '$pageview',- person_id: personId,- distinct_id: distinctId,- properties: JSON.stringify({ $browser: 'Chrome' }),- timestamp,- uuid: eventUuid,- } as RawClickHouseEvent)- ),- } as any,- ]-- // Parse messages which should create pre-calculated events- const { precalculatedEvents } = await processor._parseKafkaBatch(messages)-- // Should create one pre-calculated event for the matching cohort filter- expect(precalculatedEvents).toHaveLength(1)-- const preCalculatedEvent = precalculatedEvents[0]-- expect(preCalculatedEvent.payload).toMatchObject({- uuid: eventUuid,- team_id: team.id,- person_id: personId,- distinct_id: distinctId,- condition: conditionHash,- source: `cohort_filter_${conditionHash}`,- })- // Test publishing the events to Kafka- await processor['publishBehavioralEvents'](precalculatedEvents)-- // Check published messages to Kafka- const kafkaMessages = mockProducerObserver.getProducedKafkaMessagesForTopic(- KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS- )- expect(kafkaMessages).toHaveLength(1)-- const publishedMessage = kafkaMessages[0]- expect(publishedMessage.value).toEqual(preCalculatedEvent.payload)- })-- it('should not publish to Kafka when cohort filter does not match', async () => {- // Create a cohort with Chrome + pageview filter- const conditionHash = 'test_hash_002'- const filters = buildInlineFiltersForCohorts({- bytecode: TEST_FILTERS.chromePageview,- conditionHash,- type: 'behavioral',- key: '$pageview',- })- await createCohort(hub.postgres, team.id, 'Test cohort', filters)-- // Create a non-matching event (Firefox instead of Chrome)- const personId = '550e8400-e29b-41d4-a716-446655440000'-- const messages = [- {- value: Buffer.from(- JSON.stringify({- team_id: team.id,- event: '$pageview',- person_id: personId,- distinct_id: 'test-distinct-456',- properties: JSON.stringify({ $browser: 'Firefox' }), // Different browser- timestamp: '2025-03-03T10:15:46.319000-08:00',- uuid: 'test-uuid-2',- } as RawClickHouseEvent)- ),- } as any,- ]-- // Parse messages- const { precalculatedEvents } = await processor._parseKafkaBatch(messages)-- // Should not create any events since cohort filter doesn't match- expect(precalculatedEvents).toHaveLength(0)-- // Verify nothing was published to Kafka- await processor['publishBehavioralEvents'](precalculatedEvents)- const kafkaMessages = mockProducerObserver.getProducedKafkaMessagesForTopic(- KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS- )- expect(kafkaMessages).toHaveLength(0)- })-- it('should deduplicate filters with same conditionHash for a team', async () => {- // Create two cohorts with the same filter (same conditionHash)- const conditionHash = 'dedup_test_hash_001'- const filters = buildInlineFiltersForCohorts({ bytecode: TEST_FILTERS.pageview, conditionHash })-- // Create first cohort- await createCohort(hub.postgres, team.id, 'First cohort', filters)- // Create second cohort with same filter- await createCohort(hub.postgres, team.id, 'Second cohort', filters)-- // Create a matching event- const personId = '550e8400-e29b-41d4-a716-446655440000'- const distinctId = 'test-distinct-dedup'- const eventUuid = 'test-uuid-dedup'-- const messages = [- {- value: Buffer.from(- JSON.stringify({- team_id: team.id,- event: '$pageview',- person_id: personId,- distinct_id: distinctId,- properties: JSON.stringify({}),- timestamp: '2025-03-03T10:15:46.319000-08:00',- uuid: eventUuid,- } as RawClickHouseEvent)- ),- } as any,- ]-- // Parse messages- const { precalculatedEvents } = await processor._parseKafkaBatch(messages)-- // Should only create one event despite having two cohorts with same conditionHash- expect(precalculatedEvents).toHaveLength(1)-- const preCalculatedEvent = precalculatedEvents[0]- expect(preCalculatedEvent.payload.condition).toBe(conditionHash)- expect(preCalculatedEvent.payload.source).toBe(`cohort_filter_${conditionHash}`)- })-- it('should emit separate events for different cohorts with different conditionHashes', async () => {- // Create two cohorts with different complex filters- const conditionHash1 = 'multi_cohort_hash_001'- const conditionHash2 = 'multi_cohort_hash_002'-- // First cohort: simple pageview behavioral filter- const filters1 = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'OR',- values: [- {- key: '$pageview',- type: 'behavioral',- value: 'performed_event',- bytecode: TEST_FILTERS.pageview,- negation: false,- event_type: 'events',- conditionHash: conditionHash1,- explicit_datetime: '-30d',- },- ],- },- ],- },- })-- // Second cohort: complex behavioral filter with event_filters (AND structure)- const filters2 = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: '$pageview',- type: 'behavioral',- value: 'performed_event_multiple',- bytecode: TEST_FILTERS.chromePageview,- negation: false,- operator: 'gte',- event_type: 'events',- conditionHash: conditionHash2,- event_filters: [- { key: '$browser', type: 'event', value: 'Chrome', operator: 'exact' },- ],- operator_value: 5,- explicit_datetime: '-30d',- },- ],- },- ],- },- })-- // Create first cohort (pageview only)- await createCohort(hub.postgres, team.id, 'Pageview cohort', filters1)- // Create second cohort (Chrome + pageview with event filters)- await createCohort(hub.postgres, team.id, 'Chrome pageview cohort', filters2)-- // Create an event that matches both filters- const personId = '550e8400-e29b-41d4-a716-446655440000'- const distinctId = 'test-distinct-multi'- const eventUuid = 'test-uuid-multi'-- const messages = [- {- value: Buffer.from(- JSON.stringify({- team_id: team.id,- event: '$pageview',- person_id: personId,- distinct_id: distinctId,- properties: JSON.stringify({ $browser: 'Chrome' }),- timestamp: '2025-03-03T10:15:46.319000-08:00',- uuid: eventUuid,- } as RawClickHouseEvent)- ),- } as any,- ]-- // Parse messages- const { precalculatedEvents } = await processor._parseKafkaBatch(messages)-- // Should create two events - one for each matching cohort filter- expect(precalculatedEvents).toHaveLength(2)-- // Sort by condition hash for consistent testing- precalculatedEvents.sort((a, b) => a.payload.condition.localeCompare(b.payload.condition))-- const [event1, event2] = precalculatedEvents-- // First event should be for pageview filter- expect(event1.payload.condition).toBe(conditionHash1)- expect(event1.payload.source).toBe(`cohort_filter_${conditionHash1}`)-- // Second event should be for Chrome + pageview filter- expect(event2.payload.condition).toBe(conditionHash2)- expect(event2.payload.source).toBe(`cohort_filter_${conditionHash2}`)- })-- it('should handle complex billing cohort filter with OR/AND structure', async () => {- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: 'billing product activated',- type: 'behavioral',- value: 'performed_event',- bytecode: TEST_FILTERS.billingProductActivated,- negation: false,- event_type: 'events',- conditionHash: '2946b8444e88565c',- event_filters: [- {- key: 'product_key',- type: 'event',- value: ['platform_and_support'],- operator: 'exact',- },- {- key: 'plans__platform_and_support',- type: 'event',- value: ['teams-20240208'],- operator: 'exact',- },- ],- explicit_datetime: '-30d',- },- {- key: 'product unsubscribed',- type: 'behavioral',- value: 'performed_event',- bytecode: TEST_FILTERS.productUnsubscribed,- negation: true,- event_type: 'events',- conditionHash: '4c6bb89ec315ba80',- event_filters: [- {- key: 'product',- type: 'event',- value: ['platform_and_support'],- operator: 'exact',- },- ],- explicit_datetime: '-30d',- },- {- key: 'is_organization_first_user',- type: 'person',- value: ['true'],- bytecode: TEST_FILTERS.isOrgFirstUser,- negation: false,- operator: 'exact',- conditionHash: '7937ba56a3e6348a',- },- ],- },- ],- },- })-- await createCohort(hub.postgres, team.id, 'Billing Product Cohort', filters)-- // Test 1: Event that matches billing product activated filter- const personId1 = '950e8400-e29b-41d4-a716-446655440001'- const distinctId1 = 'billing-cohort-test-1'- const eventUuid1 = 'billing-cohort-uuid-1'- const timestamp1 = '2025-03-03T17:00:00.000000-08:00'-- const messages1 = [- {- value: Buffer.from(- JSON.stringify({- team_id: team.id,- event: 'billing product activated',- person_id: personId1,- distinct_id: distinctId1,- properties: JSON.stringify({- product_key: 'platform_and_support',- plans__platform_and_support: 'teams-20240208',- }),- timestamp: timestamp1,- uuid: eventUuid1,- } as RawClickHouseEvent)- ),- } as any,- ]-- const { precalculatedEvents: events1 } = await processor._parseKafkaBatch(messages1)-- expect(events1).toHaveLength(1)-- const preCalculatedEvent1 = events1[0]- expect(preCalculatedEvent1.payload).toMatchObject({- uuid: eventUuid1,- team_id: team.id,- person_id: personId1,- distinct_id: distinctId1,- condition: '2946b8444e88565c',- source: 'cohort_filter_2946b8444e88565c',- })- })-- it('should process person property filters and emit to person properties topic', async () => {- // Create a cohort with person property filter- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: 'is_organization_first_user',- type: 'person',- value: ['true'],- bytecode: TEST_FILTERS.isOrgFirstUser,- negation: false,- operator: 'exact',- conditionHash: 'person_prop_test_001',- },- ],- },- ],- },- })-- await createCohort(hub.postgres, team.id, 'First Org User Cohort', filters)-- const personId = '850e8400-e29b-41d4-a716-446655440002'- const distinctId = 'person-cohort-test-1'- const eventUuid = 'person-cohort-uuid-1'- const timestamp = '2025-03-03T18:00:00.000000-08:00'-- const messages = [- {- value: Buffer.from(- JSON.stringify({- team_id: team.id,- event: 'any event',- person_id: personId,- distinct_id: distinctId,- properties: JSON.stringify({}),- person_properties: JSON.stringify({- is_organization_first_user: 'true',- }),- timestamp,- uuid: eventUuid,- } as RawClickHouseEvent)- ),- } as any,- ]-- const { precalculatedEvents, precalculatedPersonProperties } = await processor._parseKafkaBatch(messages)-- // Should NOT create behavioral events- expect(precalculatedEvents).toHaveLength(0)-- // Should create person property event- expect(precalculatedPersonProperties).toHaveLength(1)- expect(precalculatedPersonProperties[0].payload).toMatchObject({- distinct_id: distinctId,- team_id: team.id,- condition: 'person_prop_test_001',- matches: true,- source: 'cohort_filter_person_prop_test_001',- })- })-- it('should produce events for negated filters', async () => {- // negated events will produce matching events- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: 'product unsubscribed',- type: 'behavioral',- value: 'performed_event',- bytecode: TEST_FILTERS.productUnsubscribed,- negation: true, // Negation flag is stored but not processed by consumer- event_type: 'events',- conditionHash: 'negated_unsub_test',- event_filters: [- {- key: 'product',- type: 'event',- value: ['platform_and_support'],- operator: 'exact',- },- ],- explicit_datetime: '-30d',- },- ],- },- ],- },- })-- await createCohort(hub.postgres, team.id, 'Not Unsubscribed Cohort', filters)-- const personId = '750e8400-e29b-41d4-a716-446655440003'- const distinctId = 'negation-test-1'- const eventUuid = 'negation-uuid-1'- const timestamp = '2025-03-03T19:00:00.000000-08:00'-- // Send a product unsubscribed event- const messages = [- {- value: Buffer.from(- JSON.stringify({- team_id: team.id,- event: 'product unsubscribed',- person_id: personId,- distinct_id: distinctId,- properties: JSON.stringify({- product: 'platform_and_support',- }),- timestamp,- uuid: eventUuid,- } as RawClickHouseEvent)- ),- } as any,- ]-- const { precalculatedEvents } = await processor._parseKafkaBatch(messages)-- // Should create an event because consumer doesn't handle negation- // It just evaluates the bytecode which will return true for matching event- expect(precalculatedEvents).toHaveLength(1)-- const preCalculatedEvent = precalculatedEvents[0]- expect(preCalculatedEvent.payload).toMatchObject({- uuid: eventUuid,- team_id: team.id,- person_id: personId,- distinct_id: distinctId,- condition: 'negated_unsub_test',- source: 'cohort_filter_negated_unsub_test',- })- })- })-})diff --git a/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.ts b/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.tsdeleted file mode 100644index 30c941baa80e..000000000000--- a/nodejs/src/cdp/consumers/cdp-precalculated-filters.consumer.ts+++ /dev/null@@ -1,329 +0,0 @@-import { Message } from 'node-rdkafka'-import { Histogram } from 'prom-client'--import { KAFKA_EVENTS_JSON } from '~/common/config/kafka-topics'-import { KafkaConsumerInterface, createKafkaConsumer } from '~/common/kafka/consumer'-import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'-import { yieldEach } from '~/common/utils/event-loop-yield'-import { parseJSON } from '~/common/utils/json-parse'-import { logger } from '~/common/utils/logger'-import {- RealtimeSupportedFilter,- RealtimeSupportedFilterManagerCDP,-} from '~/common/utils/realtime-supported-filter-manager-cdp'--import { HealthCheckResult, RawClickHouseEvent } from '../../types'-import { PRECALCULATED_PERSON_PROPERTIES_OUTPUT, PREFILTERED_EVENTS_OUTPUT } from '../outputs/outputs'-import { HogFunctionFilterGlobals } from '../types'-import { ProducedPersonPropertiesEvent } from '../types-person-properties'-import { execHog } from '../utils/hog-exec'-import { convertClickhouseRawEventToFilterGlobals } from '../utils/hog-function-filtering'-import { CdpConsumerBase, CdpConsumerBaseConfig, CdpConsumerBaseDeps } from './cdp-base.consumer'--export type PersonPropertyFilterGlobals = {- person: {- id?: string- properties: Record<string, any>- }- project: {- id: number- }-}--export type PreCalculatedEvent = {- uuid: string // event uuid- team_id: number- person_id: string- distinct_id: string- condition: string // hash of the filter bytecode- source: string-}--export type ProducedEvent = {- payload: PreCalculatedEvent-}--export const histogramBatchProcessingSteps = new Histogram({- name: 'cdp_precalculated_filters_batch_processing_steps_duration_ms',- help: 'Time spent in different batch processing steps',- labelNames: ['step'],- buckets: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500],-})--export class CdpPrecalculatedFiltersConsumer extends CdpConsumerBase {- protected name = 'CdpPrecalculatedFiltersConsumer'- private eventKafkaConsumer: KafkaConsumerInterface- private realtimeSupportedFilterManager: RealtimeSupportedFilterManagerCDP-- constructor(config: CdpConsumerBaseConfig, deps: CdpConsumerBaseDeps) {- super(config, deps)- this.eventKafkaConsumer = createKafkaConsumer({- groupId: 'cdp-precalculated-filters-consumer',- topic: KAFKA_EVENTS_JSON,- })- this.realtimeSupportedFilterManager = new RealtimeSupportedFilterManagerCDP(deps.postgres)- }-- @instrumented('cdpPrecalculatedFiltersConsumer.publishBehavioralEvents')- private async publishBehavioralEvents(events: ProducedEvent[]): Promise<void> {- if (events.length === 0) {- return- }-- try {- const messages: { value: Buffer }[] = []- await yieldEach('cdp-precalculated-filters-publish', events, (event) => {- messages.push({ value: Buffer.from(JSON.stringify(event.payload)) })- })-- await this.outputs.queueMessages(PREFILTERED_EVENTS_OUTPUT, messages)- } catch (error) {- logger.error('Error publishing behavioral events', {- error,- queueLength: events.length,- })- throw error- }- }-- @instrumented('cdpPrecalculatedFiltersConsumer.publishPersonPropertyEvents')- private async publishPersonPropertyEvents(events: ProducedPersonPropertiesEvent[]): Promise<void> {- if (events.length === 0) {- return- }-- try {- const messages: { value: Buffer }[] = []- await yieldEach('cdp-precalculated-filters-publish', events, (event) => {- messages.push({ value: Buffer.from(JSON.stringify(event.payload)) })- })-- await this.outputs.queueMessages(PRECALCULATED_PERSON_PROPERTIES_OUTPUT, messages)- } catch (error) {- logger.error('Error publishing person property events', {- error,- queueLength: events.length,- })- throw error- }- }-- // Evaluate if event matches behavioral filter using bytecode execution- private async evaluateEventAgainstRealtimeSupportedFilter(- filterGlobals: HogFunctionFilterGlobals,- filter: RealtimeSupportedFilter- ): Promise<boolean> {- if (!filter.bytecode) {- logger.error('Missing bytecode for behavioral filter', {- conditionHash: filter.conditionHash,- cohortId: filter.cohort_id,- })- return false- }-- try {- const { execResult } = await execHog(filter.bytecode, {- globals: filterGlobals,- })-- return execResult?.result ?? false- } catch (error) {- logger.error('Error executing behavioral filter bytecode', {- conditionHash: filter.conditionHash,- cohortId: filter.cohort_id,- error,- })- return false- }- }-- // Evaluate person properties against filter using bytecode execution- // Used for person_properties field from events- private async evaluatePersonPropertiesAgainstFilter(- personGlobals: PersonPropertyFilterGlobals,- filter: RealtimeSupportedFilter- ): Promise<boolean> {- if (!filter.bytecode) {- logger.error('Missing bytecode for person property filter', {- conditionHash: filter.conditionHash,- cohortId: filter.cohort_id,- })- return false- }-- try {- const { execResult } = await execHog(filter.bytecode, {- globals: personGlobals,- })-- return execResult?.result ?? false- } catch (error) {- logger.error('Error executing person property filter bytecode', {- conditionHash: filter.conditionHash,- cohortId: filter.cohort_id,- personId: personGlobals.person.id,- error,- })- return false- }- }-- // This consumer parses events from kafka and evaluates both behavioral and person property filters- @instrumented('cdpPrecalculatedFiltersConsumer.handleEachBatch.parseKafkaMessages')- public async _parseKafkaBatch(messages: Message[]): Promise<{- precalculatedEvents: ProducedEvent[]- precalculatedPersonProperties: ProducedPersonPropertiesEvent[]- }> {- const behavioralEvents: ProducedEvent[] = []- const personPropertyEvents: ProducedPersonPropertiesEvent[] = []-- // Step 1: Parse all messages and group by team_id- const eventsByTeam = new Map<number, RawClickHouseEvent[]>()-- await yieldEach('cdp-precalculated-filters-parse', messages, (message) => {- try {- const clickHouseEvent = parseJSON(message.value!.toString()) as RawClickHouseEvent-- if (!clickHouseEvent.person_id) {- logger.error('Event missing person_id', {- teamId: clickHouseEvent.team_id,- event: clickHouseEvent.event,- uuid: clickHouseEvent.uuid,- })- return // Skip events without person_id- }-- if (!eventsByTeam.has(clickHouseEvent.team_id)) {- eventsByTeam.set(clickHouseEvent.team_id, [])- }- eventsByTeam.get(clickHouseEvent.team_id)!.push(clickHouseEvent)- } catch (e) {- logger.error('Error parsing message', e)- }- })-- // Step 2: Fetch all realtime supported filters for all teams in one query- const teamIds = Array.from(eventsByTeam.keys())- const filtersByTeam = await this.realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeams(teamIds)-- // Step 3: Process each team's events with their realtime supported filters- for (const [teamId, teamEvents] of Array.from(eventsByTeam.entries())) {- try {- const filters = filtersByTeam[String(teamId)]- if (!filters) {- continue- }-- const { behavioral: behavioralFilters, person_property: personPropertyFilters } = filters-- if (behavioralFilters.length === 0 && personPropertyFilters.length === 0) {- // Skip teams with no filters- continue- }-- // Process each event for this team- await yieldEach('cdp-precalculated-filters', teamEvents, async (clickHouseEvent) => {- // Convert to filter globals for filter evaluation- const filterGlobals = convertClickhouseRawEventToFilterGlobals(clickHouseEvent)-- // Evaluate behavioral filters- for (const filter of behavioralFilters) {- const matches = await this.evaluateEventAgainstRealtimeSupportedFilter(filterGlobals, filter)-- // Only publish if event matches the filter (don't publish non-matches)- if (matches) {- const preCalculatedEvent: ProducedEvent = {- payload: {- uuid: filterGlobals.uuid,- team_id: clickHouseEvent.team_id,- person_id: clickHouseEvent.person_id!,- distinct_id: filterGlobals.distinct_id,- condition: filter.conditionHash,- source: `cohort_filter_${filter.conditionHash}`,- },- }-- behavioralEvents.push(preCalculatedEvent)- }- }-- // Evaluate person property filters using person_properties from the event- if (personPropertyFilters.length > 0 && clickHouseEvent.person_properties) {- const personProperties = parseJSON(clickHouseEvent.person_properties)-- const personGlobals: PersonPropertyFilterGlobals = {- person: {- id: clickHouseEvent.person_id,- properties: personProperties,- },- project: {- id: clickHouseEvent.team_id,- },- }-- for (const filter of personPropertyFilters) {- const matches = await this.evaluatePersonPropertiesAgainstFilter(personGlobals, filter)-- // CRITICAL: Always emit - both matches AND non-matches- // Person properties are mutable state, need to track changes- const personPropertyEvent: ProducedPersonPropertiesEvent = {- payload: {- distinct_id: clickHouseEvent.distinct_id,- person_id: clickHouseEvent.person_id!,- team_id: clickHouseEvent.team_id,- condition: filter.conditionHash,- matches: matches,- source: `cohort_filter_${filter.conditionHash}`,- },- }-- personPropertyEvents.push(personPropertyEvent)- }- }- })- } catch (e) {- logger.error('Error processing team events', { teamId, error: e })- }- }- return { precalculatedEvents: behavioralEvents, precalculatedPersonProperties: personPropertyEvents }- }-- public override async start(): Promise<void> {- await super.start()-- await this.eventKafkaConsumer.connect(async (messages) => {- logger.info('🔁', `${this.name} - handling event batch`, {- size: messages.length,- })-- return await instrumentFn('cdpPrecalculatedFiltersConsumer.handleEventBatch', async () => {- const { precalculatedEvents, precalculatedPersonProperties } = await this._parseKafkaBatch(messages)-- // Publish both types of events in parallel- const backgroundTask = Promise.all([- this.publishBehavioralEvents(precalculatedEvents).catch((error) => {- throw new Error(`Failed to publish behavioral events: ${error.message}`)- }),- this.publishPersonPropertyEvents(precalculatedPersonProperties).catch((error) => {- throw new Error(`Failed to publish person property events: ${error.message}`)- }),- ])-- return { backgroundTask }- })- })- }-- public override async stop(): Promise<void> {- logger.info('💤', `Stopping ${this.name}...`)- await this.eventKafkaConsumer.disconnect()-- // IMPORTANT: super always comes last- await super.stop()- logger.info('💤', `${this.name} stopped!`)- }-- public isHealthy(): HealthCheckResult {- return this.eventKafkaConsumer.isHealthy()- }-}diff --git a/nodejs/src/cdp/outputs/outputs.ts b/nodejs/src/cdp/outputs/outputs.tsindex 87baf85c3af4..fefb8cd96ae8 100644--- a/nodejs/src/cdp/outputs/outputs.ts+++ b/nodejs/src/cdp/outputs/outputs.ts@@ -7,11 +7,5 @@* driven by the registry build in `registry.ts`.*/-export const PREFILTERED_EVENTS_OUTPUT = 'prefiltered_events' as const-export type PrefilteredEventsOutput = typeof PREFILTERED_EVENTS_OUTPUT--export const PRECALCULATED_PERSON_PROPERTIES_OUTPUT = 'precalculated_person_properties' as const-export type PrecalculatedPersonPropertiesOutput = typeof PRECALCULATED_PERSON_PROPERTIES_OUTPUT-export const WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT = 'warehouse_source_webhooks' as constexport type WarehouseSourceWebhooksOutput = typeof WAREHOUSE_SOURCE_WEBHOOKS_OUTPUTdiff --git a/nodejs/src/cdp/outputs/producer-registry.ts b/nodejs/src/cdp/outputs/producer-registry.tsindex cecfe9a85579..2c7f588daf90 100644--- a/nodejs/src/cdp/outputs/producer-registry.ts+++ b/nodejs/src/cdp/outputs/producer-registry.ts@@ -16,9 +16,10 @@ import {** - `WARPSTREAM_INGESTION_PRODUCER` — hog function monitoring (app metrics +* log entries). Targets the warpstream-ingestion cluster.- * - `WARPSTREAM_CALCULATED_EVENTS_PRODUCER` — dedicated cluster for the- * precalculated-filters consumer's outputs (`clickhouse_prefiltered_events`,- * `clickhouse_precalculated_person_properties`).+ * - `WARPSTREAM_CALCULATED_EVENTS_PRODUCER` — dedicated calculated-events+ * cluster. No CDP output routes to it now that the precalculated-filters+ * consumer is gone; kept registered because charts still supply its env vars+ * and registration is lazy. Reuse it for the next calculated-events output.* - `WARPSTREAM_CYCLOTRON_PRODUCER` — Cyclotron Warpstream cluster used for* batch hogflow request enqueue. Distinct env-var prefix from the legacy* `KAFKA_CDP_PRODUCER_*` so output routing is decoupled from the cyclotrondiff --git a/nodejs/src/cdp/outputs/producers.ts b/nodejs/src/cdp/outputs/producers.tsindex 57aa924f53bc..93ac3f0cdf0b 100644--- a/nodejs/src/cdp/outputs/producers.ts+++ b/nodejs/src/cdp/outputs/producers.ts@@ -16,8 +16,9 @@ export const WAREHOUSE_PRODUCER = 'WAREHOUSE_PRODUCER' as constexport type WarehouseProducer = typeof WAREHOUSE_PRODUCER/**- * Targets the dedicated Warpstream cluster for clickhouse precalculated /- * prefiltered events (`KAFKA_WARPSTREAM_CALCULATED_EVENTS_PRODUCER_*`).+ * Targets the dedicated Warpstream calculated-events cluster+ * (`KAFKA_WARPSTREAM_CALCULATED_EVENTS_PRODUCER_*`). Currently unused — see+ * `createCdpProducerRegistry` for why it stays registered.*/export const WARPSTREAM_CALCULATED_EVENTS_PRODUCER = 'WARPSTREAM_CALCULATED_EVENTS_PRODUCER' as constexport type WarpstreamCalculatedEventsProducer = typeof WARPSTREAM_CALCULATED_EVENTS_PRODUCERdiff --git a/nodejs/src/cdp/outputs/registry.ts b/nodejs/src/cdp/outputs/registry.tsindex 61d2f18b21c0..3fddd544bc31 100644--- a/nodejs/src/cdp/outputs/registry.ts+++ b/nodejs/src/cdp/outputs/registry.ts@@ -6,11 +6,7 @@ import {} from '~/common/outputs'import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'-import {- PRECALCULATED_PERSON_PROPERTIES_OUTPUT,- PREFILTERED_EVENTS_OUTPUT,- WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT,-} from './outputs'+import { WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT } from './outputs'/*** Outputs the CDP deployments write to. Each output's topic + producer are@@ -20,8 +16,6 @@ import {* - `APP_METRICS_OUTPUT` + `LOG_ENTRIES_OUTPUT` — hog function monitoring path* (also used for legacy plugin app metrics since they share the* `clickhouse_app_metrics2` schema).- * - `PREFILTERED_EVENTS_OUTPUT` + `PRECALCULATED_PERSON_PROPERTIES_OUTPUT` —- * precalculated-filters consumer writes to ClickHouse.* - `WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT` — warehouse source webhook payloads.*/export function createCdpOutputsRegistry() {@@ -42,14 +36,6 @@ export function createCdpOutputsRegistry() {topicKey: 'MESSAGE_ASSETS_TOPIC',producerKey: 'MESSAGE_ASSETS_PRODUCER',})- .register(PREFILTERED_EVENTS_OUTPUT, {- topicKey: 'CDP_PREFILTERED_EVENTS_TOPIC',- producerKey: 'CDP_PREFILTERED_EVENTS_PRODUCER',- })- .register(PRECALCULATED_PERSON_PROPERTIES_OUTPUT, {- topicKey: 'CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC',- producerKey: 'CDP_PRECALCULATED_PERSON_PROPERTIES_PRODUCER',- }).register(WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT, {topicKey: 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC',producerKey: 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER',diff --git a/nodejs/src/cdp/types-person-properties.ts b/nodejs/src/cdp/types-person-properties.tsdeleted file mode 100644index d2addb6a07e4..000000000000--- a/nodejs/src/cdp/types-person-properties.ts+++ /dev/null@@ -1,14 +0,0 @@-// TypeScript types for precalculated person properties events--export type PreCalculatedPersonProperties = {- distinct_id: string- person_id: string- team_id: number- condition: string // 16-char conditionHash- matches: boolean // true = matches, false = doesn't match- source: string // e.g., "cohort_filter_{conditionHash}"-}--export type ProducedPersonPropertiesEvent = {- payload: PreCalculatedPersonProperties-}diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 94d52a9ea8b8..68f0ab6f3cb9 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -31,6 +31,8 @@ export enum PluginServerMode {cdp_data_warehouse_events = 'cdp-data-warehouse-events',cdp_internal_events = 'cdp-internal-events',cdp_cyclotron_worker = 'cdp-cyclotron-worker',+ // TODO: remove once charts stop setting PLUGIN_SERVER_MODE=cdp-precalculated-filters.+ // The consumer is gone; an unknown mode would throw at boot, so keep the member until then.cdp_precalculated_filters = 'cdp-precalculated-filters',cdp_hogflow_subscription_matcher = 'cdp-hogflow-subscription-matcher',cdp_cohort_membership = 'cdp-cohort-membership',diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.tsindex c928dae67e21..52607ad7353e 100644--- a/nodejs/src/common/config/kafka-topics.ts+++ b/nodejs/src/common/config/kafka-topics.ts@@ -67,8 +67,6 @@ export const KAFKA_MESSAGE_ASSETS = `${prefix}clickhouse_message_assets${suffix}export const KAFKA_CDP_FUNCTION_OVERFLOW = `${prefix}cdp_function_overflow${suffix}`export const KAFKA_CDP_INTERNAL_EVENTS = `${prefix}cdp_internal_events${suffix}`export const KAFKA_CDP_CLICKHOUSE_BEHAVIORAL_COHORTS_MATCHES = `${prefix}clickhouse_behavioral_cohorts_matches${suffix}`-export const KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS = `${prefix}clickhouse_prefiltered_events${suffix}`-export const KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES = `${prefix}clickhouse_precalculated_person_properties${suffix}`export const KAFKA_COHORT_MEMBERSHIP_CHANGED = `${prefix}cohort_membership_changed${suffix}`// Cross-partition merge protocol trigger consumed by the cohort-stream-processor (Rust).export const KAFKA_PERSON_MERGE_EVENTS = `${prefix}person_merge_events${suffix}`diff --git a/nodejs/src/common/utils/realtime-supported-filter-manager-cdp.test.ts b/nodejs/src/common/utils/realtime-supported-filter-manager-cdp.test.tsdeleted file mode 100644index 0cca1f405a4f..000000000000--- a/nodejs/src/common/utils/realtime-supported-filter-manager-cdp.test.ts+++ /dev/null@@ -1,657 +0,0 @@-import {- buildInlineFiltersForCohorts,- createCohort,- createTeam,- getFirstTeam,- resetTestDatabase,-} from '~/tests/helpers/sql'-import { Hub, Team } from '~/types'--import { defaultConfig } from '../config/config'-import { closeHub, createHub } from './db/hub'-import { PostgresRouter } from './db/postgres'-import { RealtimeSupportedFilterManagerCDP } from './realtime-supported-filter-manager-cdp'--describe('RealtimeSupportedFilterManagerCDP()', () => {- let hub: Hub- let realtimeSupportedFilterManager: RealtimeSupportedFilterManagerCDP- let postgres: PostgresRouter- let teamId: Team['id']- let fetchRealtimeSupportedFiltersSpy: jest.SpyInstance-- beforeEach(async () => {- const now = Date.now()- jest.spyOn(Date, 'now').mockImplementation(() => now)-- hub = await createHub()- await resetTestDatabase()-- postgres = new PostgresRouter(defaultConfig)- realtimeSupportedFilterManager = new RealtimeSupportedFilterManagerCDP(postgres)- const team = await getFirstTeam(hub.postgres)- teamId = team.id- fetchRealtimeSupportedFiltersSpy = jest.spyOn(- realtimeSupportedFilterManager as any,- 'fetchRealtimeSupportedFilters'- )- })-- afterEach(async () => {- await closeHub(hub)- })-- describe('getRealtimeSupportedFiltersForTeam()', () => {- it('returns empty array if no realtime cohorts exist', async () => {- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result).toEqual({ behavioral: [], person_property: [] })- })-- it('returns realtime supported filters for a team', async () => {- const bytecode = ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 1, 2, 11]- const conditionHash = 'test_hash_001'- const filters = buildInlineFiltersForCohorts({ bytecode, conditionHash, key: '$browser' })-- // Create a realtime cohort- const cohortId = await createCohort(postgres, teamId, 'Test Cohort', filters)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result.behavioral).toHaveLength(1)- expect(result.behavioral[0]).toMatchObject({- conditionHash: conditionHash,- bytecode: bytecode,- team_id: teamId,- cohort_id: cohortId,- })- })-- it('filters out deleted cohorts', async () => {- const bytecode = ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 1, 2, 11]- const filters = buildInlineFiltersForCohorts({- bytecode,- conditionHash: 'test_hash_001',- key: '$browser',- })-- // Create active cohort- await createCohort(postgres, teamId, 'Active Cohort', filters)-- // Create deleted cohort- await createCohort(postgres, teamId, 'Deleted Cohort', filters, { deleted: true })-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result.behavioral).toHaveLength(1)- expect(result.behavioral[0].cohort_id).not.toBe('Deleted Cohort')- })-- it('filters out cohorts without filters', async () => {- // Create cohort without filters (uses default empty filters)- await createCohort(postgres, teamId, 'No Filters Cohort', null)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result).toEqual({ behavioral: [], person_property: [] })- })-- it('filters out non-realtime cohorts', async () => {- const bytecode = ['_H', 1, 32, 'test']- const filters = buildInlineFiltersForCohorts({ bytecode, conditionHash: 'test_hash_001' })-- // Create behavioral cohort (not realtime)- await createCohort(postgres, teamId, 'Behavioral Cohort', filters, { cohort_type: 'behavioral' })-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result).toEqual({ behavioral: [], person_property: [] })- })-- it('deduplicates filters by conditionHash across complex nested structures', async () => {- const combinedBytecode = [- '_H',- 1,- 32,- '$pageview',- 32,- 'event',- 1,- 1,- 11,- 31,- 32,- '$browser',- 32,- 'properties',- 1,- 2,- 12,- 31,- 32,- '$browser_language',- 32,- 'properties',- 1,- 2,- 12,- 3,- 2,- 3,- 2,- ]- const conditionHash = 'bcdc95b22cf3e527'-- // Complex filter structure matching the user's example- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: '$pageview',- type: 'behavioral',- value: 'performed_event_multiple',- bytecode: combinedBytecode,- negation: false,- operator: 'exact',- event_type: 'events',- conditionHash: conditionHash,- event_filters: [- { key: '$browser', type: 'event', value: 'is_set', operator: 'is_set' },- {- key: '$browser_language',- type: 'event',- value: 'is_set',- operator: 'is_set',- },- ],- operator_value: 5,- explicit_datetime: '-30d',- },- ],- },- ],- },- })-- // Create two cohorts with the same conditionHash in complex structures- await createCohort(postgres, teamId, 'Cohort 1', filters)- await createCohort(postgres, teamId, 'Cohort 2', filters)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result.behavioral).toHaveLength(1) // Should be deduplicated- expect(result.behavioral[0].conditionHash).toBe(conditionHash)- expect(result.behavioral[0].bytecode).toEqual(combinedBytecode)- })-- it('handles multiple filters in single cohort with complex nested structure', async () => {- // Complex filter: behavioral filter with event_filters (combined bytecode)- const behavioralWithEventFilterBytecode = [- '_H',- 1,- 32,- '$pageview',- 32,- 'event',- 1,- 1,- 11,- 31,- 32,- '$browser',- 32,- 'properties',- 1,- 2,- 12,- 3,- 2,- ]- const pageviewOnlyBytecode = ['_H', 1, 32, '$pageleave', 32, 'event', 1, 1, 11]-- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: '$pageview',- type: 'behavioral',- value: 'performed_event_multiple',- bytecode: behavioralWithEventFilterBytecode,- negation: false,- operator: 'gte',- event_type: 'events',- conditionHash: '512ef57e6f504fc6',- event_filters: [- { key: '$browser', type: 'event', value: 'is_set', operator: 'is_set' },- ],- operator_value: 5,- explicit_datetime: '-30d',- },- {- key: '$pageleave',- type: 'behavioral',- value: 'performed_event',- bytecode: pageviewOnlyBytecode,- negation: false,- event_type: 'events',- conditionHash: 'e0418e34fcd847e5',- explicit_datetime: '-30d',- },- ],- },- ],- },- })-- await createCohort(postgres, teamId, 'Multi-Filter Cohort', filters)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result.behavioral).toHaveLength(2)- expect(result.behavioral.map((f) => f.conditionHash).sort()).toEqual([- '512ef57e6f504fc6',- 'e0418e34fcd847e5',- ])- // Verify the combined bytecode for the behavioral filter with event_filters- const behavioralFilter = result.behavioral.find((f) => f.conditionHash === '512ef57e6f504fc6')- expect(behavioralFilter?.bytecode).toEqual(behavioralWithEventFilterBytecode)- })-- it('filters out person property bytecodes explicitly via type in complex structure', async () => {- const personPropBytecode = ['_H', 1, 31, 32, '$host', 32, 'properties', 32, 'person', 1, 3, 12]- const behavioralBytecode = ['_H', 1, 32, '$pageview', 32, 'event', 1, 1, 11]-- // Complex structure with both person and behavioral filters - only behavioral should be extracted- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: '$pageview',- type: 'behavioral',- value: 'performed_event',- bytecode: behavioralBytecode,- negation: false,- event_type: 'events',- conditionHash: 'e0418e34fcd847e5',- explicit_datetime: '-30d',- },- {- key: '$host',- type: 'person',- bytecode: personPropBytecode,- negation: false,- operator: 'is_set',- conditionHash: '30b9607b69c556bf',- },- ],- },- ],- },- })-- await createCohort(postgres, teamId, 'Mixed Filters Cohort', filters)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- // Should split behavioral and person property filters- expect(result.behavioral).toHaveLength(1)- expect(result.behavioral[0].conditionHash).toBe('e0418e34fcd847e5')- expect(result.behavioral[0].bytecode).toEqual(behavioralBytecode)- expect(result.person_property).toHaveLength(1)- expect(result.person_property[0].conditionHash).toBe('30b9607b69c556bf')- expect(result.person_property[0].bytecode).toEqual(personPropBytecode)- })-- it('filters out cohort filters and only keeps event filters', async () => {- // This test uses the exact structure from the user's example- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'OR',- values: [- {- key: 'id',- type: 'cohort',- value: 41,- bytecode: ['_H', 1, 33, 41, 2, 'inCohort', 1],- negation: false,- conditionHash: '5e6d68bd7c7babae',- },- ],- },- {- type: 'OR',- values: [- {- key: '$pageview',- type: 'behavioral',- value: 'performed_event',- bytecode: ['_H', 1, 32, '$pageview', 32, 'event', 1, 1, 11],- negation: false,- event_type: 'events',- conditionHash: 'f9c616030a87e68f',- explicit_datetime: '-30d',- },- ],- },- ],- },- })-- await createCohort(postgres, teamId, 'Cohort with InCohort Filter', filters)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)-- // Should filter out the cohort filter and only return the event filter- expect(result.behavioral).toHaveLength(1)- expect(result.behavioral[0].conditionHash).toBe('f9c616030a87e68f')- expect(result.behavioral[0].bytecode).toEqual(['_H', 1, 32, '$pageview', 32, 'event', 1, 1, 11])-- // Verify the cohort filter was filtered out- const cohortFilter = result.behavioral.find((f) => f.conditionHash === '5e6d68bd7c7babae')- expect(cohortFilter).toBeUndefined()- })-- it('handles complex OR structure with multiple filter groups', async () => {- // Test structure with OR at top level containing multiple groups (matching user's second example)- const pageviewWithBrowserBytecode = [- '_H',- 1,- 32,- '$pageview',- 32,- 'event',- 1,- 1,- 11,- 31,- 32,- '$browser',- 32,- 'properties',- 1,- 2,- 12,- 3,- 2,- ]- const pageleaveBytecode = ['_H', 1, 32, '$pageleave', 32, 'event', 1, 1, 11]- const groupidentifyBytecode = [- '_H',- 1,- 32,- '$groupidentify',- 32,- 'event',- 1,- 1,- 11,- 31,- 32,- 'id',- 32,- 'properties',- 1,- 2,- 12,- 3,- 2,- ]-- const filters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'AND',- values: [- {- key: '$pageview',- type: 'behavioral',- value: 'performed_event_multiple',- bytecode: pageviewWithBrowserBytecode,- negation: false,- operator: 'gte',- event_type: 'events',- conditionHash: '512ef57e6f504fc6',- event_filters: [- { key: '$browser', type: 'event', value: 'is_set', operator: 'is_set' },- ],- operator_value: 5,- explicit_datetime: '-30d',- },- {- key: '$pageleave',- type: 'behavioral',- value: 'performed_event',- bytecode: pageleaveBytecode,- negation: false,- event_type: 'events',- conditionHash: 'e0418e34fcd847e5',- explicit_datetime: '-30d',- },- ],- },- {- type: 'OR',- values: [- {- key: '$groupidentify',- type: 'behavioral',- value: 'performed_event',- bytecode: groupidentifyBytecode,- negation: false,- event_type: 'events',- conditionHash: 'f0bbe0140a9cfe05',- event_filters: [{ key: 'id', type: 'event', value: 'is_set', operator: 'is_set' }],- explicit_datetime: '-30d',- },- ],- },- ],- },- })-- await createCohort(postgres, teamId, 'Complex OR Cohort', filters)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result.behavioral).toHaveLength(3)- const hashes = result.behavioral.map((f) => f.conditionHash).sort()- expect(hashes).toEqual(['512ef57e6f504fc6', 'e0418e34fcd847e5', 'f0bbe0140a9cfe05'])-- // Verify all bytecodes are correctly extracted- expect(result.behavioral.find((f) => f.conditionHash === '512ef57e6f504fc6')?.bytecode).toEqual(- pageviewWithBrowserBytecode- )- expect(result.behavioral.find((f) => f.conditionHash === 'e0418e34fcd847e5')?.bytecode).toEqual(- pageleaveBytecode- )- expect(result.behavioral.find((f) => f.conditionHash === 'f0bbe0140a9cfe05')?.bytecode).toEqual(- groupidentifyBytecode- )- })-- it('handles malformed filters gracefully', async () => {- const validBytecode = ['_H', 1, 32, 'test']- const validFilters = buildInlineFiltersForCohorts({ bytecode: validBytecode, conditionHash: 'valid_hash' })-- // Create cohort with valid filters- await createCohort(postgres, teamId, 'Valid Cohort', validFilters)-- // Create cohort with malformed filters (missing bytecode/conditionHash)- const malformedFilters = JSON.stringify({- properties: {- type: 'OR',- values: [- {- type: 'OR',- values: [- {- key: '$test',- type: 'behavioral',- // Missing bytecode and conditionHash- },- ],- },- ],- },- })- await createCohort(postgres, teamId, 'Malformed Cohort', malformedFilters)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result.behavioral).toHaveLength(1) // Only valid filter should be returned- expect(result.behavioral[0].conditionHash).toBe('valid_hash')- })-- it('caches filters for subsequent calls', async () => {- const bytecode = ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 1, 2, 11]- const filters = buildInlineFiltersForCohorts({- bytecode,- conditionHash: 'cached_hash',- key: '$browser',- })-- await createCohort(postgres, teamId, 'Cached Cohort', filters)-- // First call- const result1 = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result1.behavioral).toHaveLength(1)- expect(fetchRealtimeSupportedFiltersSpy).toHaveBeenCalledTimes(1)-- // Second call should use cache- const result2 = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result2.behavioral).toHaveLength(1)- expect(fetchRealtimeSupportedFiltersSpy).toHaveBeenCalledTimes(1)- })-- it('returns empty array for non-existent team', async () => {- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(99999)- expect(result).toEqual({ behavioral: [], person_property: [] })- })- })-- describe('getRealtimeSupportedFiltersForTeams()', () => {- it('returns filters for multiple teams', async () => {- const bytecode = ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 1, 2, 11]- const filters1 = buildInlineFiltersForCohorts({- bytecode,- conditionHash: 'team1_hash',- key: '$browser',- })- const filters2 = buildInlineFiltersForCohorts({- bytecode,- conditionHash: 'team2_hash',- key: '$browser',- })-- // Create another team- const team = await hub.teamManager.getTeam(teamId)- const team2Id = await createTeam(postgres, team!.organization_id)-- // Create cohorts for both teams- await createCohort(postgres, teamId, 'Team 1 Cohort', filters1)- await createCohort(postgres, team2Id, 'Team 2 Cohort', filters2)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeams([teamId, team2Id])- expect(result[String(teamId)].behavioral).toHaveLength(1)- expect(result[String(teamId)].behavioral[0].conditionHash).toBe('team1_hash')- expect(result[String(team2Id)].behavioral).toHaveLength(1)- expect(result[String(team2Id)].behavioral[0].conditionHash).toBe('team2_hash')- })-- it('returns empty arrays for teams with no realtime cohorts', async () => {- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeams([teamId, 99999])- expect(result[String(teamId)]).toEqual({ behavioral: [], person_property: [] })- expect(result['99999']).toEqual({ behavioral: [], person_property: [] })- })-- it('efficiently loads multiple teams with single database call', async () => {- const bytecode = ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 1, 2, 11]- const filters = buildInlineFiltersForCohorts({- bytecode,- conditionHash: 'test_hash',- key: '$browser',- })-- await createCohort(postgres, teamId, 'Test Cohort', filters)-- const promises = [- realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId),- realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId),- realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(99999),- ]-- const results = await Promise.all(promises)- expect(fetchRealtimeSupportedFiltersSpy).toHaveBeenCalledTimes(1)- expect(results[0].behavioral).toHaveLength(1)- expect(results[1].behavioral).toHaveLength(1)- expect(results[2].behavioral).toHaveLength(0)- })-- it('deduplicates filters across multiple teams', async () => {- const bytecode = ['_H', 1, 32, 'shared', 32, 'filter']- const sharedHash = 'shared_condition_hash'- const filters = buildInlineFiltersForCohorts({ bytecode, conditionHash: sharedHash })-- // Create another team- const team = await hub.teamManager.getTeam(teamId)- const team2Id = await createTeam(postgres, team!.organization_id)-- // Create cohorts with same conditionHash for both teams- await createCohort(postgres, teamId, 'Team 1 Cohort', filters)- await createCohort(postgres, team2Id, 'Team 2 Cohort', filters)-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeams([teamId, team2Id])-- // Should be deduplicated - only one filter per team even though they have same hash- expect(result[String(teamId)].behavioral).toHaveLength(1)- expect(result[String(team2Id)].behavioral).toHaveLength(1)- expect(result[String(teamId)].behavioral[0].conditionHash).toBe(sharedHash)- expect(result[String(team2Id)].behavioral[0].conditionHash).toBe(sharedHash)- })- })-- describe('fetchRealtimeSupportedFilters()', () => {- it('handles empty team ID array', async () => {- const result = await (realtimeSupportedFilterManager as any).fetchRealtimeSupportedFilters([])- expect(result).toEqual({})- })-- it('handles invalid team IDs', async () => {- const result = await (realtimeSupportedFilterManager as any).fetchRealtimeSupportedFilters([- 'invalid',- 'NaN',- ])- expect(result).toEqual({})- })-- it('orders cohorts by team_id and created_at DESC', async () => {- const bytecode = ['_H', 1, 32, 'test']-- // Create cohorts with different created_at times- const olderTime = new Date(Date.now() - 3600000).toISOString() // 1 hour ago- const newerTime = new Date().toISOString()-- const olderFilters = buildInlineFiltersForCohorts({ bytecode, conditionHash: 'older_hash' })- const newerFilters = buildInlineFiltersForCohorts({ bytecode, conditionHash: 'newer_hash' })-- await createCohort(postgres, teamId, 'Older Cohort', olderFilters, {- created_at: olderTime,- })-- await createCohort(postgres, teamId, 'Newer Cohort', newerFilters, {- created_at: newerTime,- })-- const result = await realtimeSupportedFilterManager.getRealtimeSupportedFiltersForTeam(teamId)- expect(result.behavioral).toHaveLength(2)- expect(result.behavioral[0].conditionHash).toBe('newer_hash') // Should be first due to DESC order- expect(result.behavioral[1].conditionHash).toBe('older_hash')- })- })-})diff --git a/nodejs/src/common/utils/realtime-supported-filter-manager-cdp.ts b/nodejs/src/common/utils/realtime-supported-filter-manager-cdp.tsdeleted file mode 100644index 20c03d4ac299..000000000000--- a/nodejs/src/common/utils/realtime-supported-filter-manager-cdp.ts+++ /dev/null@@ -1,202 +0,0 @@-import { PostgresRouter, PostgresUse } from './db/postgres'-import { LazyLoader } from './lazy-loader'-import { logger } from './logger'--/**- * Type of filter for realtime cohort evaluation.- *- * - 'behavioral': Event-based filters that require processing event streams (e.g., "performed pageview")- * - 'person_property': Person property filters evaluated against person state (e.g., "email is set")- */-export type FilterType = 'behavioral' | 'person_property'--export interface RealtimeSupportedFilter {- conditionHash: string // The 16-char SHA256 hash from the filter- bytecode: any // HogQL bytecode for execution- team_id: number- cohort_id: number // For tracking which cohort this filter belongs to- filter_type: FilterType // 'behavioral' for event filters, 'person_property' for person filters-}--export interface RealtimeSupportedFiltersByType {- behavioral: RealtimeSupportedFilter[]- person_property: RealtimeSupportedFilter[]-}--interface CohortRow {- cohort_id: number- team_id: number- filters: any | null // JSON object (PostgreSQL deserializes JSON/JSONB columns automatically)-}--export class RealtimeSupportedFilterManagerCDP {- private lazyLoader: LazyLoader<RealtimeSupportedFiltersByType>-- constructor(private postgres: PostgresRouter) {- this.lazyLoader = new LazyLoader({- name: 'RealtimeSupportedFilterManagerCDP',- refreshAgeMs: 5 * 60 * 1000, // 5 minutes- refreshJitterMs: 60 * 1000, // 1 minute- loader: async (teamIds: string[]) => {- return await this.fetchRealtimeSupportedFilters(teamIds)- },- })- }-- public async getRealtimeSupportedFiltersForTeam(teamId: number): Promise<RealtimeSupportedFiltersByType> {- const filters = await this.lazyLoader.get(String(teamId))- if (!filters) {- return { behavioral: [], person_property: [] }- }- return filters- }-- public async getRealtimeSupportedFiltersForTeams(- teamIds: number[]- ): Promise<Record<string, RealtimeSupportedFiltersByType>> {- const allFilters = await this.lazyLoader.getMany(teamIds.map(String))-- // Ensure all entries have valid filter objects (not null)- const result: Record<string, RealtimeSupportedFiltersByType> = {}- for (const [teamId, filters] of Object.entries(allFilters)) {- result[teamId] = filters || { behavioral: [], person_property: [] }- }-- return result- }-- private async fetchRealtimeSupportedFilters(- teamIds: string[]- ): Promise<Record<string, RealtimeSupportedFiltersByType>> {- const teamIdNumbers = teamIds.map(Number).filter((id) => !isNaN(id))-- if (teamIdNumbers.length === 0) {- return {}- }-- const result = await this.postgres.query<CohortRow>(- PostgresUse.COMMON_READ,- `SELECT- id as cohort_id,- team_id,- filters- FROM posthog_cohort- WHERE team_id = ANY($1)- AND deleted = FALSE- AND filters IS NOT NULL- AND cohort_type = 'realtime'- ORDER BY team_id, created_at DESC`,- [teamIdNumbers],- 'fetch-realtime-supported-filters-by-team'- )-- // Initialize result record with empty filter arrays for all requested team IDs- const resultRecord: Record<string, RealtimeSupportedFiltersByType> = {}- for (const teamId of teamIds) {- resultRecord[teamId] = { behavioral: [], person_property: [] }- }-- // Process filters from each cohort and deduplicate by conditionHash per team- const seenConditionHashesByTeam = new Map<string, Set<string>>()-- result.rows.forEach((cohortRow) => {- const teamIdStr = String(cohortRow.team_id)-- if (!resultRecord[teamIdStr]) {- resultRecord[teamIdStr] = { behavioral: [], person_property: [] }- }-- if (!seenConditionHashesByTeam.has(teamIdStr)) {- seenConditionHashesByTeam.set(teamIdStr, new Set<string>())- }-- const teamSeenHashes = seenConditionHashesByTeam.get(teamIdStr)!- const filtersJson = cohortRow.filters || {}-- const extracted = this.extractRealtimeFiltersFromFiltersJson(filtersJson, cohortRow, teamSeenHashes)- resultRecord[teamIdStr].behavioral.push(...extracted.behavioral)- resultRecord[teamIdStr].person_property.push(...extracted.person_property)- })-- return resultRecord- }-- // Extracts realtime-executable filters from a cohort's filters JSON- private extractRealtimeFiltersFromFiltersJson(- filtersJson: any,- cohortRow: CohortRow,- teamSeenHashes: Set<string>- ): RealtimeSupportedFiltersByType {- const collected: RealtimeSupportedFiltersByType = {- behavioral: [],- person_property: [],- }-- const visitLeaf = (node: any) => {- // Only accept leaf nodes that have inline bytecode and conditionHash- if (!node || !node.conditionHash || !node.bytecode) {- return- }-- // Skip cohort filters (recursive cohort references)- if (node.type === 'cohort') {- return- }-- // Determine filter type based on node type- let filterType: FilterType- if (node.type === 'person') {- filterType = 'person_property'- } else if (node.type === 'behavioral') {- filterType = 'behavioral'- } else {- logger.warn('Unknown filter type, skipping', {- filterType: node.type,- conditionHash: node.conditionHash,- cohortId: cohortRow.cohort_id,- })- return- }-- const conditionHash = node.conditionHash as string- if (teamSeenHashes.has(conditionHash)) {- return- }- teamSeenHashes.add(conditionHash)-- const filter: RealtimeSupportedFilter = {- conditionHash,- bytecode: node.bytecode,- team_id: cohortRow.team_id,- cohort_id: cohortRow.cohort_id,- filter_type: filterType,- }-- // Add to the appropriate array based on filter type- collected[filterType].push(filter)- }-- if (filtersJson && filtersJson.properties) {- this.traverseFilterTree(filtersJson.properties, visitLeaf)- }-- return collected- }-- // Generic DFS over the filter tree; calls visit on every leaf node- private traverseFilterTree(node: any, visit: (leaf: any) => void): void {- if (!node) {- return- }- const isGroup = node.type === 'OR' || node.type === 'AND'- if (isGroup) {- if (Array.isArray(node.values)) {- for (const child of node.values) {- this.traverseFilterTree(child, visit)- }- }- return- }- visit(node)- }-}diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 6072465ea18a..85047596ec19 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -34,7 +34,6 @@ import { CdpHogflowSubscriptionMatcherConsumer } from './cdp/consumers/cdp-hogflimport { CdpInternalEventsConsumer } from './cdp/consumers/cdp-internal-event.consumer'import { CdpLegacyEventsConsumer } from './cdp/consumers/cdp-legacy-event.consumer'import { CdpPersonUpdatesConsumer } from './cdp/consumers/cdp-person-updates-consumer'-import { CdpPrecalculatedFiltersConsumer } from './cdp/consumers/cdp-precalculated-filters.consumer'import { CdpRerunWorkerConsumer } from './cdp/consumers/cdp-rerun-worker.consumer'import { createCdpProducerRegistry } from './cdp/outputs/producer-registry'import { CdpProducerName } from './cdp/outputs/producers'@@ -103,7 +102,6 @@ export class PluginServer implements NodeServer {capabilities.cdpCyclotronWorkerHogFlowLegacyPg ||capabilities.cdpCyclotronWorkerEmail ||capabilities.cdpCyclotronWorkerEmailLegacyPg ||- capabilities.cdpPrecalculatedFilters ||capabilities.cdpCohortMembership ||capabilities.cdpCyclotronWorkerBatchResolve ||capabilities.cdpHogflowSubscriptionMatcher ||@@ -402,14 +400,6 @@ export class PluginServer implements NodeServer {return Promise.resolve(serverCommands.service)})- if (capabilities.cdpPrecalculatedFilters) {- serviceLoaders.push(async () => {- const worker = new CdpPrecalculatedFiltersConsumer(this.config, cdpDeps!)- await worker.start()- return worker.service- })- }-if (capabilities.cdpCohortMembership) {serviceLoaders.push(async () => {const consumer = new CdpCohortMembershipConsumer(this.config, cdpDeps!)diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex 6fee25911170..07880732b1f1 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -148,7 +148,6 @@ export interface PluginServerCapabilities {cdpCyclotronWorkerHogFlowLegacyPg?: booleancdpCyclotronWorkerEmail?: booleancdpCyclotronWorkerEmailLegacyPg?: boolean- cdpPrecalculatedFilters?: booleancdpCohortMembership?: booleancdpApi?: booleanappManagementSingleton?: booleandiff --git a/nodejs/tests/helpers/kafka.ts b/nodejs/tests/helpers/kafka.tsindex bc7a9b9afd63..551b9b25fad0 100644--- a/nodejs/tests/helpers/kafka.ts+++ b/nodejs/tests/helpers/kafka.ts@@ -5,7 +5,6 @@ import {KAFKA_APP_METRICS_2,KAFKA_BUFFER,KAFKA_CDP_CLICKHOUSE_BEHAVIORAL_COHORTS_MATCHES,- KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,KAFKA_CLICKHOUSE_AI_EVENTS_JSON,KAFKA_CLICKHOUSE_HEATMAP_EVENTS,KAFKA_CLICKHOUSE_SESSION_RECORDING_EVENTS,@@ -99,7 +98,6 @@ export const TEST_KAFKA_TOPICS = [KAFKA_EVENTS_RECENT_JSON,KAFKA_ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES,KAFKA_CDP_CLICKHOUSE_BEHAVIORAL_COHORTS_MATCHES,- KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,KAFKA_COHORT_MEMBERSHIP_CHANGED,KAFKA_PERSON_MERGE_EVENTS,KAFKA_CLICKHOUSE_TOPHOG,diff --git a/posthog/admin/admins/backfill_precalculated_events_admin.py b/posthog/admin/admins/backfill_precalculated_events_admin.pydeleted file mode 100644index c78b9dafb888..000000000000--- a/posthog/admin/admins/backfill_precalculated_events_admin.py+++ /dev/null@@ -1,107 +0,0 @@-from django import forms-from django.contrib import admin, messages-from django.core.exceptions import PermissionDenied-from django.core.management import call_command-from django.shortcuts import redirect, render---class BackfillPrecalculatedEventsForm(forms.Form):- team_id = forms.IntegerField(- min_value=1,- help_text="Team ID for the cohort",- label="Team ID",- )- cohort_id = forms.IntegerField(- required=False,- help_text="Optional: Specific cohort ID to backfill. If not provided, backfills all realtime cohorts for the team",- label="Cohort ID",- )- days = forms.IntegerField(- required=False,- min_value=1,- max_value=90,- help_text="Override the backfill time window in days (default: auto-computed from filters, max: 90)",- label="Days to backfill",- )- concurrent_workflows = forms.IntegerField(- required=False,- initial=5,- min_value=1,- max_value=100,- help_text="Number of concurrent child workflows to run (1-100, default: 5)",- label="Concurrent workflows",- )- ignore_backfilled_dates = forms.BooleanField(- required=False,- initial=False,- help_text="Skip the already-backfilled check and reprocess all days unconditionally",- label="Ignore backfilled dates",- )-- def clean_concurrent_workflows(self):- value = self.cleaned_data.get("concurrent_workflows")- if value is None:- return 5- return value---def backfill_precalculated_events_view(request):- """Custom admin view for backfilling precalculated_events table."""- if not request.user.is_staff:- raise PermissionDenied-- if request.method == "POST":- form = BackfillPrecalculatedEventsForm(request.POST)- if form.is_valid():- command_args = []- command_args.extend(["--team-id", str(form.cleaned_data["team_id"])])-- if form.cleaned_data.get("cohort_id"):- command_args.extend(["--cohort-id", str(form.cleaned_data["cohort_id"])])-- if form.cleaned_data.get("days"):- command_args.extend(["--days", str(form.cleaned_data["days"])])-- command_args.extend(["--concurrent-workflows", str(form.cleaned_data["concurrent_workflows"])])-- if form.cleaned_data.get("ignore_backfilled_dates"):- command_args.append("--ignore-backfilled-dates")-- try:- call_command("backfill_precalculated_events", *command_args)-- cohort_info = (- f"cohort {form.cleaned_data['cohort_id']}"- if form.cleaned_data.get("cohort_id")- else "all realtime cohorts"- )- days_info = (- f" for {form.cleaned_data['days']} days"- if form.cleaned_data.get("days")- else " (auto-computed window)"- )- force_info = ", ignoring backfilled dates" if form.cleaned_data.get("ignore_backfilled_dates") else ""- messages.success(- request,- f"Event backfill started successfully for {cohort_info}{days_info}{force_info} "- f"(team {form.cleaned_data['team_id']}) "- f"with {form.cleaned_data['concurrent_workflows']} concurrent workflows. "- f"Check Temporal UI for progress.",- )- except Exception as e:- messages.error(request, f"Failed to start backfill: {str(e)}")-- return redirect("backfill-precalculated-events")- else:- form = BackfillPrecalculatedEventsForm()-- context = {- "form": form,- "title": "Backfill Precalculated Events",- "has_view_permission": True,- "site_title": admin.site.site_title,- "site_header": admin.site.site_header,- "site_url": admin.site.site_url,- "has_permission": True,- }- return render(request, "admin/backfill_precalculated_events.html", context)diff --git a/posthog/admin/admins/backfill_precalculated_person_properties_admin.py b/posthog/admin/admins/backfill_precalculated_person_properties_admin.pydeleted file mode 100644index 7e87049dfc37..000000000000--- a/posthog/admin/admins/backfill_precalculated_person_properties_admin.py+++ /dev/null@@ -1,101 +0,0 @@-from django import forms-from django.contrib import admin, messages-from django.core.exceptions import PermissionDenied-from django.core.management import call_command-from django.shortcuts import redirect, render---class BackfillPrecalculatedPersonPropertiesForm(forms.Form):- team_id = forms.IntegerField(- min_value=1,- help_text="Team ID for the cohort",- label="Team ID",- )- cohort_id = forms.IntegerField(- required=False,- help_text="Optional: Specific cohort ID to backfill. If not provided, backfills all realtime cohorts for the team",- label="Cohort ID",- )- batch_size = forms.IntegerField(- initial=1000,- min_value=100,- help_text="Number of persons to process per batch using ID-range based batching",- label="Batch size",- )- concurrent_workflows = forms.IntegerField(- initial=5,- min_value=1,- max_value=100,- help_text="Number of concurrent child workflows to run (1-100, default: 5)",- label="Concurrent workflows",- )- person_id = forms.UUIDField(- required=False,- help_text="Optional: Specific person ID (UUID) to filter the backfill for. If provided, only processes properties for this person",- label="Person ID",- )---def backfill_precalculated_person_properties_view(request):- """- Custom admin view for backfilling precalculated_person_properties table.- No model needed - just a form that triggers a management command.- """- if not request.user.is_staff:- raise PermissionDenied-- if request.method == "POST":- form = BackfillPrecalculatedPersonPropertiesForm(request.POST)- if form.is_valid():- command_args = []- command_args.extend(["--team-id", str(form.cleaned_data["team_id"])])-- # Only add cohort_id if provided- if form.cleaned_data.get("cohort_id"):- command_args.extend(["--cohort-id", str(form.cleaned_data["cohort_id"])])-- command_args.extend(["--batch-size", str(form.cleaned_data["batch_size"])])- command_args.extend(["--concurrent-workflows", str(form.cleaned_data["concurrent_workflows"])])-- # Only add person_id if provided- if form.cleaned_data.get("person_id"):- command_args.extend(["--person-id", str(form.cleaned_data["person_id"])])-- try:- call_command("backfill_precalculated_person_properties", *command_args)-- cohort_info = (- f"cohort {form.cleaned_data['cohort_id']}"- if form.cleaned_data.get("cohort_id")- else "all realtime cohorts"- )- person_info = (- f" (filtered to person {form.cleaned_data['person_id']})"- if form.cleaned_data.get("person_id")- else ""- )- messages.success(- request,- f"Backfill started successfully for {cohort_info}{person_info} "- f"(team {form.cleaned_data['team_id']}) "- f"using ID-range based batching with {form.cleaned_data['batch_size']} persons per batch "- f"and {form.cleaned_data['concurrent_workflows']} concurrent workflows. "- f"Check Temporal UI for progress.",- )- except Exception as e:- messages.error(request, f"Failed to start backfill: {str(e)}")-- return redirect("backfill-precalculated-person-properties")- else:- form = BackfillPrecalculatedPersonPropertiesForm()-- context = {- "form": form,- "title": "Backfill Precalculated Person Properties",- "has_view_permission": True,- "site_title": admin.site.site_title,- "site_header": admin.site.site_header,- "site_url": admin.site.site_url,- "has_permission": True,- }- return render(request, "admin/backfill_precalculated_person_properties.html", context)diff --git a/posthog/admin/admins/realtime_cohort_calculation_admin.py b/posthog/admin/admins/realtime_cohort_calculation_admin.pydeleted file mode 100644index 03ce2937f998..000000000000--- a/posthog/admin/admins/realtime_cohort_calculation_admin.py+++ /dev/null@@ -1,123 +0,0 @@-import math--from django import forms-from django.contrib import admin, messages-from django.core.exceptions import PermissionDenied-from django.core.management import call_command-from django.shortcuts import redirect, render---class RealtimeCohortCalculationForm(forms.Form):- parallelism = forms.IntegerField(- initial=10,- min_value=1,- max_value=50,- help_text="Number of parallel child workflows to spawn",- label="Parallelism",- )- workflows_per_batch = forms.IntegerField(- initial=5,- min_value=1,- max_value=20,- help_text="Number of workflows to start per batch for jittered scheduling",- label="Workflows per batch",- )- batch_delay_minutes = forms.IntegerField(- initial=5,- min_value=1,- max_value=60,- help_text="Delay between batches in minutes",- label="Batch delay (minutes)",- )- team_ids = forms.CharField(- required=False,- help_text="Comma-separated list of team IDs that should process all cohorts (optional)",- label="Team IDs",- )-- def clean_team_ids(self):- """Validate team_ids format."""- team_ids_str = self.cleaned_data.get("team_ids")- if not team_ids_str:- return None-- team_ids_str = team_ids_str.strip()- if not team_ids_str:- return None-- try:- team_ids = {int(tid.strip()) for tid in team_ids_str.split(",") if tid.strip()}- if not team_ids:- raise forms.ValidationError("At least one valid team ID is required.")- return team_ids_str- except ValueError:- raise forms.ValidationError("Team IDs must be comma-separated integers (e.g., '2,42,100').")-- global_percentage = forms.FloatField(- required=False,- min_value=0.0,- max_value=1.0,- help_text="Global percentage for teams not in team-ids list (0.0 to 1.0, optional)",- label="Global Percentage",- )- cohort_id = forms.IntegerField(- required=False,- min_value=1,- help_text="Filter to a specific cohort_id (optional)",- label="Cohort ID",- )---def analyze_realtime_cohort_calculation_view(request):- """- Custom admin view for realtime cohort calculation.- No model needed - just a form that triggers a management command.- """- if not request.user.is_staff:- raise PermissionDenied-- if request.method == "POST":- form = RealtimeCohortCalculationForm(request.POST)- if form.is_valid():- command_args = []- command_args.extend(["--parallelism", str(form.cleaned_data["parallelism"])])- command_args.extend(["--workflows-per-batch", str(form.cleaned_data["workflows_per_batch"])])- command_args.extend(["--batch-delay-minutes", str(form.cleaned_data["batch_delay_minutes"])])- if form.cleaned_data.get("team_ids"):- command_args.extend(["--team-ids", form.cleaned_data["team_ids"]])- if form.cleaned_data.get("global_percentage") is not None:- command_args.extend(["--global-percentage", str(form.cleaned_data["global_percentage"])])- if form.cleaned_data.get("cohort_id"):- command_args.extend(["--cohort-id", str(form.cleaned_data["cohort_id"])])-- try:- call_command("analyze_realtime_cohort_calculation", *command_args)-- total_batches = math.ceil(form.cleaned_data["parallelism"] / form.cleaned_data["workflows_per_batch"])- total_time_minutes = (total_batches - 1) * form.cleaned_data["batch_delay_minutes"]-- messages.success(- request,- f"Realtime cohort calculation started successfully with {form.cleaned_data['parallelism']} workflows "- f"in {total_batches} batches ({form.cleaned_data['workflows_per_batch']} per batch, "- f"{form.cleaned_data['batch_delay_minutes']}min delays). "- f"All workflows will be scheduled over ~{total_time_minutes} minutes. "- f"Check Temporal UI for progress.",- )- except Exception as e:- messages.error(request, f"Failed to start realtime cohort calculation: {str(e)}")-- return redirect("realtime-cohorts-calculation")- else:- form = RealtimeCohortCalculationForm()-- context = {- "form": form,- "title": "Realtime Cohort Calculation",- "has_view_permission": True,- "site_title": admin.site.site_title,- "site_header": admin.site.site_header,- "site_url": admin.site.site_url,- "has_permission": True,- }- return render(request, "admin/realtime_cohort_calculation.html", context)diff --git a/posthog/admin/test_backfill_precalculated_events_admin.py b/posthog/admin/test_backfill_precalculated_events_admin.pydeleted file mode 100644index f61ba83ecd9a..000000000000--- a/posthog/admin/test_backfill_precalculated_events_admin.py+++ /dev/null@@ -1,43 +0,0 @@-from posthog.test.base import BaseTest-from unittest.mock import patch--from django.contrib.messages.storage.fallback import FallbackStorage-from django.test import RequestFactory--from parameterized import parameterized--from posthog.admin.admins.backfill_precalculated_events_admin import backfill_precalculated_events_view---def _attach_messages(request) -> None:- request.session = {}- request._messages = FallbackStorage(request)---class TestBackfillPrecalculatedEventsAdmin(BaseTest):- def setUp(self) -> None:- super().setUp()- self.user.is_staff = True- self.user.save()- self.factory = RequestFactory()-- @parameterized.expand([(True,), (False,)])- def test_ignore_backfilled_dates_checkbox_controls_command_flag(self, ignore_backfilled_dates: bool) -> None:- data = {"team_id": "2", "cohort_id": "123", "concurrent_workflows": "5"}- if ignore_backfilled_dates:- data["ignore_backfilled_dates"] = "on"- request = self.factory.post("/admin/backfill-precalculated-events/", data)- request.user = self.user- _attach_messages(request)-- with (- patch("posthog.admin.admins.backfill_precalculated_events_admin.call_command") as mock_call_command,- patch("posthog.admin.admins.backfill_precalculated_events_admin.redirect") as mock_redirect,- ):- backfill_precalculated_events_view(request)-- mock_call_command.assert_called_once()- command_args = mock_call_command.call_args[0]- assert command_args[0] == "backfill_precalculated_events"- assert ("--ignore-backfilled-dates" in command_args) is ignore_backfilled_dates- mock_redirect.assert_called_once_with("backfill-precalculated-events")diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 04b1d0f2e873..a8648cdc9086 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -410,9 +410,10 @@ def _calculate_realtime_support(group: CohortFilterGroup) -> bool:return Falseelse: # It's a filter# person_metadata reads top-level persons-table columns, which the realtime- # precalculated_person_properties table doesn't carry. Any cohort referencing one- # must use the standard (non-realtime) calculation path, so force the whole cohort- # non-realtime as soon as a person_metadata filter appears in any group.+ # evaluator's person scope doesn't expose (it carries only person.id and+ # person.properties). Any cohort referencing one must use the standard+ # (non-realtime) calculation path, so force the whole cohort non-realtime as+ # soon as a person_metadata filter appears in any group.if getattr(value, "type", None) == "person_metadata":return False# Check if filter has FilterBytecodeMixin and valid bytecodediff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex abbc0d434849..54ee55eb445b 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -6540,8 +6540,8 @@ class TestCohortTypeIntegration(APIBaseTest):def test_person_metadata_cohort_not_classified_realtime(self):"""person_metadata cohorts must route to the non-realtime path: the realtime- precalculated_person_properties table only carries JSON-blob values, not top-level- persons-table columns, so HogQLRealtimeCohortQuery raises for them."""+ evaluator's person scope exposes only person.id and person.properties, not+ top-level persons-table columns."""response = self.client.post(f"/api/projects/{self.team.id}/cohorts/",diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex 5bef8659a85a..b043866eaa6c 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -1,6 +1,4 @@-from collections import defaultdict, namedtuple-from copy import deepcopy-from datetime import datetime+from collections import namedtuplefrom numbers import Numberfrom typing import Any, Literal, Optional, Union, cast@@ -36,9 +34,9 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.ast import SelectQuery, SelectSetNode, SelectSetQuery-from posthog.hogql.constants import HogQLGlobalSettings, HogQLQuerySettings, LimitContext+from posthog.hogql.constants import HogQLGlobalSettings, LimitContextfrom posthog.hogql.context import HogQLContext-from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.property import get_property_typefrom posthog.hogql.query import HogQLQueryExecutor@@ -46,7 +44,6 @@ from posthog.hogql.query import HogQLQueryExecutorfrom posthog.constants import PropertyOperatorTypefrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.events_query_runner import EventsQueryRunner-from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models import Filter, Property, Team, Userfrom posthog.models.property import OperatorInterval, PropertyGroupfrom posthog.ph_client import feature_enabled_or_false@@ -91,20 +88,6 @@ def _require_select_query(query: ast.SelectQuery | ast.SelectSetQuery) -> ast.Sereturn query-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.@@ -818,814 +801,3 @@ class HogQLCohortQuery:if condition.negation:raise ValidationError("Top level condition cannot be negated", str(self.property_groups))return condition.query---class HogQLRealtimeCohortQuery(HogQLCohortQuery):- """- Realtime cohort query that uses prefiltered_events for behavioral conditions- and cohort_membership for child cohort filters.-- This extends HogQLCohortQuery and overrides the methods that need to query- different tables for realtime cohort calculation.- """-- # Operators that support merging into IN clauses- MERGEABLE_OPERATORS = {"icontains", "not_icontains", "exact", "is_not"}-- def __init__(- self,- filter: Optional[Filter] = None,- cohort: Optional[Cohort] = None,- team: Optional[Team] = None,- ):- super().__init__(filter=filter, cohort=cohort, team=team)- self.cohort = cohort- # Preprocess to merge properties with same key and operator- self.property_groups = self._preprocess_property_groups(self.property_groups) # type: ignore[assignment]-- def _should_combine_person_properties_and(self) -> bool:- """Realtime cohorts should not use AND combining optimization."""- return False-- def _should_combine_person_properties_or(self) -> bool:- """Realtime cohorts should not use OR combining optimization."""- return False-- def _is_mergeable_property(self, prop: Property) -> bool:- """Check if a property can be merged with others."""- return (- prop.type == "person"- and prop.operator in self.MERGEABLE_OPERATORS- and not prop.negation- and hasattr(prop, "conditionHash")- and bool(prop.conditionHash)- )-- def _deduplicate_hashes(self, hashes: list[str]) -> list[str]:- """- Deduplicate hashes while preserving order.-- Deduplication is necessary for an edge case: if the same filter appears twice- (e.g., user accidentally added "email contains @gmail.com" twice), we need to- ensure the count matches the distinct conditions in the GROUP BY condition query.- Without deduplication, HAVING matching_count = 2 would fail because IN would only- match 1 distinct condition.- """- # dict.fromkeys() preserves insertion order in Python 3.7+ and is more efficient- return list(dict.fromkeys(hashes))-- def _create_merged_property(self, template: Property, unique_hashes: list[str], is_or_group: bool) -> Property:- """- Create a merged property from a template with multiple condition hashes.-- Args:- template: Property to use as template for the merged property- unique_hashes: List of condition hashes to merge (must be non-empty)- is_or_group: Whether this merge is for OR semantics (True) or AND semantics (False)-- Raises:- ValueError: If unique_hashes is empty- """- if not unique_hashes:- raise ValueError(f"Cannot create merged property with empty unique_hashes. Template property: {template}")-- merged_prop = deepcopy(template)- merged_prop._merged_condition_hashes = unique_hashes # type: ignore[attr-defined]- merged_prop._is_or_group = is_or_group # type: ignore[attr-defined]- return merged_prop-- def _unwrap_single_property_groups(- self, prop_or_group: Union[Property, PropertyGroup]- ) -> Union[Property, PropertyGroup]:- """- Unwrap PropertyGroups that contain only a single child.-- unwrap_cohort creates nested PropertyGroups like:- PropertyGroup(AND) -> PropertyGroup(AND) -> Property-- This unwraps them to just: Property- """- if not isinstance(prop_or_group, PropertyGroup):- return prop_or_group-- # Recursively unwrap children first- unwrapped_values: list[Union[Property, PropertyGroup]] = [- self._unwrap_single_property_groups(v) for v in prop_or_group.values- ]- prop_or_group.values = cast(Union[list[Property], list[PropertyGroup]], unwrapped_values)-- # If this group has only one child, return the child instead- if len(prop_or_group.values) == 1:- return prop_or_group.values[0]-- return prop_or_group-- def _preprocess_property_groups(self, prop_group: Optional[PropertyGroup]) -> Optional[PropertyGroup]:- """- Preprocess property groups to merge person properties with same key and operator.-- For example, multiple email contains filters become a single merged property with- multiple conditionHashes that will be queried with IN clause.- """-- if not prop_group or not isinstance(prop_group, PropertyGroup):- return prop_group-- # First, unwrap deeply nested single-property groups- unwrapped = self._unwrap_single_property_groups(prop_group)- if not isinstance(unwrapped, PropertyGroup):- # If unwrapping resulted in a single Property, wrap it back in a PropertyGroup- # so it can be processed normally- single_property_group = PropertyGroup(type=PropertyOperatorType.AND, values=[unwrapped])- return single_property_group- prop_group = unwrapped-- # Process both AND and OR groups for merging- is_and_group = prop_group.type == PropertyOperatorType.AND- is_or_group = prop_group.type == PropertyOperatorType.OR-- if not is_and_group and not is_or_group:- # For other group types, just recursively process children- processed_values: list[Union[Property, PropertyGroup]] = [- cast(Union[Property, PropertyGroup], self._preprocess_property_groups(v))- if isinstance(v, PropertyGroup)- else v- for v in prop_group.values- ]- prop_group.values = cast(Union[list[Property], list[PropertyGroup]], processed_values)- return prop_group-- # Group person properties by (key, operator)- groups: dict[tuple[str, str], list[Property]] = defaultdict(list)- non_mergeable: list[Union[Property, PropertyGroup]] = []-- for value in prop_group.values:- if isinstance(value, PropertyGroup):- processed = self._preprocess_property_groups(value)- if processed is not None:- non_mergeable.append(processed)- elif isinstance(value, Property):- if self._is_mergeable_property(value):- key = (value.key, str(value.operator))- groups[key].append(value)- else:- non_mergeable.append(value)-- # Merge groups with 2+ properties- merged_values: list[Union[Property, PropertyGroup]] = []- for props in groups.values():- if len(props) >= 2:- # Collect and deduplicate hashes- hashes = [p.conditionHash for p in props if p.conditionHash]- unique_hashes = self._deduplicate_hashes(hashes)- # Only create merged property if we have condition hashes to merge- if unique_hashes:- # Create merged property- merged_prop = self._create_merged_property(props[0], unique_hashes, is_or_group)- merged_values.append(merged_prop)- else:- # No condition hashes available, keep properties as-is- merged_values.extend(props)- else:- merged_values.extend(props)-- merged_values.extend(non_mergeable)- prop_group.values = cast(Union[list[Property], list[PropertyGroup]], merged_values)-- # After merging within groups, also merge sibling single-property groups- prop_group = self._merge_sibling_single_property_groups(prop_group)-- return prop_group-- def _merge_sibling_single_property_groups(self, prop_group: PropertyGroup) -> PropertyGroup:- """- Merge sibling single-property groups under an OR that have the same key and operator.-- Example:- OR:- - AND: [email icontains @gmail.com, email is_not [email protected]]- ↑ Can't merge: multi-value group with different operators (icontains vs is_not)- - OR: [email icontains yahoo.com] # single property, can merge- - OR: [email icontains @protonmail.com, email icontains @live.com] # already merged-- Result: Last two OR groups merge into one with 3 hashes (yahoo + protonmail + live).- The AND group stays separate because it has multiple values and mixed operators.- """- if prop_group.type != PropertyOperatorType.OR:- return prop_group-- # Collect hashes by (key, operator) and track templates for creating merged properties- mergeable_by_key: dict[tuple[str, str], list[str]] = defaultdict(list)- first_property_by_key: dict[tuple[str, str], Property] = {}- other_values: list[Union[Property, PropertyGroup]] = []-- for value in prop_group.values:- # Extract child from single-value groups or plain properties- child = None- if isinstance(value, PropertyGroup) and len(value.values) == 1:- child = value.values[0]- elif isinstance(value, Property):- child = value- else:- # Multi-value groups can't be merged- other_values.append(value)- continue-- if isinstance(child, Property) and self._is_mergeable_property(child):- key = (child.key, str(child.operator))-- # Collect hashes: property may already be merged (has multiple hashes) or single hash- if hasattr(child, "_merged_condition_hashes"):- mergeable_by_key[key].extend(child._merged_condition_hashes)- elif hasattr(child, "conditionHash") and child.conditionHash:- mergeable_by_key[key].append(child.conditionHash)- else:- other_values.append(value)- continue-- # Save first property as template for merged property- if key not in first_property_by_key:- first_property_by_key[key] = child- else:- other_values.append(value)-- # Create merged properties for each (key, operator) with 2+ unique hashes- merged_values: list[Union[Property, PropertyGroup]] = []- for key, hashes in mergeable_by_key.items():- unique_hashes = self._deduplicate_hashes(hashes)-- if len(unique_hashes) >= 2:- template = first_property_by_key[key]- merged_prop = self._create_merged_property(template, unique_hashes, is_or_group=True)- merged_values.append(merged_prop)- elif len(unique_hashes) == 1:- # Single hash after dedup: wrap back in group to preserve structure- template = first_property_by_key[key]- single_prop = deepcopy(template)- # Safely remove merged attributes if they exist- for attr in ["_merged_condition_hashes", "_is_or_group"]:- if hasattr(single_prop, attr):- delattr(single_prop, attr)- merged_values.append(PropertyGroup(type=PropertyOperatorType.OR, values=[single_prop]))-- merged_values.extend(other_values)- prop_group.values = cast(Union[list[Property], list[PropertyGroup]], merged_values)- return prop_group-- def _should_combine_person_properties(self) -> bool:- """- Override parent class to disable person property combining optimization for realtime cohorts.-- Why disabled:- - Parent class (HogQLCohortQuery) combines multiple person properties into a single query- against the `persons` table using AND(condition1, condition2, ...) logic- - Realtime cohorts use `precalculated_person_properties` table where each property- has a unique conditionHash for fast lookup- - Each conditionHash must be queried separately or combined using IN clauses- - Our property merging optimization (in _preprocess_property_groups) already handles- combining properties with the same key+operator using IN clauses-- Returns:- False to disable the parent's combining optimization- """- return False-- def get_performed_event_condition(self, prop: Property, first_time: bool = False) -> ast.SelectQuery:- """- Query precalculated_events using conditionHash for realtime behavioral matching.- Uses the precalculated_events table populated by CdpRealtimeCohortsConsumer.- """- condition_hash = getattr(prop, "conditionHash", None)- if not condition_hash:- cohort_id = self.cohort.id if self.cohort else "unknown"- raise ValueError(- f"BUG: Realtime cohort (cohort_id={cohort_id}) has behavioral property without conditionHash. "- f"All realtime cohorts MUST have conditionHash for behavioral filters. Property: {prop}"- )-- # Extract date_from using same logic as parent class- if prop.explicit_datetime:- # Explicit datetime filter, can be a relative or absolute date- date_from_str = prop.explicit_datetime- date_to_str = prop.explicit_datetime_to- else:- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")- date_interval = validate_interval(prop.time_interval)- date_from_str = f"-{date_value}{date_interval[:1]}"- date_to_str = None-- # Parse the date string using QueryDateRange to get actual datetime- date_range = DateRange(date_from=date_from_str, date_to=date_to_str)- query_date_range = QueryDateRange(- date_range=date_range,- team=self.team,- interval=None,- now=datetime.now(),- )- date_from_datetime = query_date_range.date_from()- date_to_datetime = query_date_range.date_to() if date_to_str else None-- # Build date filter - include date_to if provided for range filtering- date_filter = "date >= toDate({date_from})"- if date_to_datetime:- date_filter = "date >= toDate({date_from}) AND date <= toDate({date_to})"-- # 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 DISTINCT- person_id as id- 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] = {- "team_id": ast.Constant(value=self.team.pk),- "condition_hash": ast.Constant(value=condition_hash),- "date_from": ast.Constant(value=date_from_datetime),- }- if date_to_datetime:- query_params["date_to"] = ast.Constant(value=date_to_datetime)-- return _apply_in_order_aggregation(cast(ast.SelectQuery, parse_select(query_str, query_params)))-- def get_performed_event_multiple(self, prop: Property) -> ast.SelectQuery:- """- Query precalculated_events with count aggregation for multiple event occurrences.- Supports operators: gte, lte, gt, lt, eq.- """- condition_hash = getattr(prop, "conditionHash", None)- if not condition_hash:- cohort_id = self.cohort.id if self.cohort else "unknown"- raise ValueError(- f"Realtime cohort (cohort_id={cohort_id}) has behavioral property without conditionHash. "- f"All realtime cohorts MUST have conditionHash for behavioral filters. Property: {prop}"- )-- min_matches = parse_and_validate_positive_integer(prop.operator_value, "operator_value")-- # Extract date_from using same logic as parent class- if prop.explicit_datetime:- # Explicit datetime filter, can be a relative or absolute date- date_from_str = prop.explicit_datetime- date_to_str = prop.explicit_datetime_to- else:- date_value = parse_and_validate_positive_integer(prop.time_value, "time_value")- date_interval = validate_interval(prop.time_interval)- date_from_str = f"-{date_value}{date_interval[:1]}"- date_to_str = None-- # Parse the date string using QueryDateRange to get actual datetime- date_range = DateRange(date_from=date_from_str, date_to=date_to_str)- query_date_range = QueryDateRange(- date_range=date_range,- team=self.team,- interval=None,- now=datetime.now(),- )- date_from_datetime = query_date_range.date_from()- date_to_datetime = query_date_range.date_to() if date_to_str else None-- # Map operator to SQL comparison - validated to prevent SQL injection- VALID_OPERATORS: dict[str, str] = {- "gte": ">=",- "lte": "<=",- "gt": ">",- "lt": "<",- "eq": "=",- "exact": "=",- }- operator_str = str(prop.operator) if prop.operator else "eq"- if operator_str not in VALID_OPERATORS:- raise ValidationError(- f"Invalid operator for performed_event_multiple: {prop.operator}. "- f"Must be one of: {', '.join(VALID_OPERATORS.keys())}"- )- sql_operator = VALID_OPERATORS[operator_str]-- # Build date filter - include date_to if provided for range filtering- date_filter = "date >= toDate({date_from})"- if date_to_datetime:- date_filter = "date >= toDate({date_from}) AND date <= toDate({date_to})"-- query_str = f"""- SELECT- person_id as id- 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_id- HAVING count() {sql_operator} {{min_matches}}- """-- query_params: dict[str, ast.Expr] = {- "team_id": ast.Constant(value=self.team.pk),- "condition_hash": ast.Constant(value=condition_hash),- "date_from": ast.Constant(value=date_from_datetime),- "min_matches": ast.Constant(value=min_matches),- }- if date_to_datetime:- query_params["date_to"] = ast.Constant(value=date_to_datetime)-- return _apply_in_order_aggregation(- cast(- ast.SelectQuery,- parse_select(query_str, query_params),- )- )-- def get_dynamic_cohort_condition(self, prop: Property) -> ast.SelectQuery:- """- Query cohort_membership table for realtime cohort membership.- Filters most recent status='entered' to find current members.- """- if isinstance(prop.value, list):- raise ValueError(f"cohort id must be an integer, got {prop.value}")- cohort_id = parse_and_validate_positive_integer(prop.value, "cohort id")-- return cast(- ast.SelectQuery,- parse_select(- """- SELECT person_id as id FROM (- SELECT person_id, argMax(status, last_updated) as status- FROM cohort_membership- WHERE cohort_id = {cohort_id}- AND team_id = {team_id}- GROUP BY person_id- HAVING status = 'entered'- )- """,- {- "cohort_id": ast.Constant(value=cohort_id),- "team_id": ast.Constant(value=self.team.pk),- },- ),- )-- def _build_single_condition_query(self, condition_hash: str) -> ast.SelectQuery:- """One-pass query for a single condition: latest match per person via argMax.-- No outer aggregation is needed when there's only one condition, so this avoids the- second GROUP BY pass that the counting query below would otherwise do for N=1.- """- query_str = """- SELECT- person_id as id- FROM precalculated_person_properties- WHERE- team_id = {team_id}- AND condition = {condition_hash}- GROUP BY person_id- HAVING argMax(matches, (_timestamp, _offset)) = 1- """-- return cast(- ast.SelectQuery,- parse_select(- query_str,- {- "team_id": ast.Constant(value=self.team.pk),- "condition_hash": ast.Constant(value=condition_hash),- },- ),- )-- def _build_count_match_query(self, hashes: list[str], operator: PropertyOperatorType) -> ast.SelectQuery:- """Build a single-scan query counting how many of `hashes` each person matches.-- One pass over precalculated_person_properties: compute the latest match state per- (person, condition) with argMax, then count matching conditions per person. Peak group- count is still O(persons × conditions) (person_id isn't a prefix of the table's ORDER BY,- so the inner aggregation can't stream), but what fixes the OOM is the constant factor:- N full-table scans collapse into one, and each group holds a tiny argMax(Bool) state- instead of N materialized person-UUID sets joined by INTERSECT/UNION DISTINCT.-- AND: every condition must match → HAVING countIf(...) >= N- OR: at least one must match → HAVING countIf(...) >= 1-- `>= N` is used for AND rather than `= N`: hashes are deduplicated and the inner- GROUP BY person_id, condition emits at most one row per condition, so countIf can never- exceed N. The two are equivalent, and a single operator keeps one query path.- """- deduplicated = self._deduplicate_hashes(hashes)- # A single condition needs no cross-condition counting; use the cheaper one-pass query.- if len(deduplicated) == 1:- return self._build_single_condition_query(deduplicated[0])-- threshold = len(deduplicated) if operator == PropertyOperatorType.AND else 1- having = parse_expr("countIf(latest_matches = 1) >= {threshold}", {"threshold": ast.Constant(value=threshold)})- return self._single_scan_membership_query(deduplicated, having)-- def _single_scan_membership_query(self, hashes: list[str], having: ast.Expr) -> ast.SelectQuery:- """Assemble the single-scan SELECT over precalculated_person_properties for a given HAVING expr.-- Shared scaffold for both the flat-count path (_build_count_match_query) and the boolean-tree- path (_build_boolean_tree_query): one inner GROUP BY (person_id, condition) with argMax, one- outer GROUP BY person_id with HAVING. Keeping the scan template in one place ensures future- changes to the table access pattern (sort key, column renames, extra filters) are applied- consistently.- """- query_str = """- SELECT- person_id as id- FROM- (- SELECT- person_id,- condition,- argMax(matches, (_timestamp, _offset)) as latest_matches- FROM precalculated_person_properties- WHERE- team_id = {team_id}- AND condition IN {condition_hashes}- GROUP BY person_id, condition- )- GROUP BY person_id- HAVING {having}- """-- return cast(- ast.SelectQuery,- parse_select(- query_str,- {- "team_id": ast.Constant(value=self.team.pk),- "condition_hashes": ast.Tuple(exprs=[ast.Constant(value=h) for h in hashes]),- "having": having,- },- ),- )-- def get_person_condition(self, prop: Property) -> ast.SelectQuery:- """- Query precalculated_person_properties using conditionHash for realtime person property matching.- Table for precalculated person properties evaluations populated by CdpRealtimeCohortsConsumer and backfill workflows.-- If prop has _merged_condition_hashes, uses IN clause to combine multiple conditions.- """- # Check if this property was merged in preprocessing- merged_hashes = getattr(prop, "_merged_condition_hashes", None)-- if merged_hashes is not None:- # Validate that merged_hashes is not empty to prevent invalid SQL generation- if not merged_hashes:- cohort_id = self.cohort.id if self.cohort else "unknown"- raise ValueError(- f"BUG: Realtime cohort (cohort_id={cohort_id}) has merged property with empty condition hashes. "- f"This would generate invalid SQL with empty IN clause. Property: {prop}"- )-- # Check if this is from an OR group (OR semantics) or AND group (AND semantics)- is_or_group = getattr(prop, "_is_or_group", False)- operator = PropertyOperatorType.OR if is_or_group else PropertyOperatorType.AND- return self._build_count_match_query(merged_hashes, operator)- else:- # Single condition - original logic- condition_hash = getattr(prop, "conditionHash", None)- if not condition_hash:- cohort_id = self.cohort.id if self.cohort else "unknown"- raise ValueError(- f"BUG: Realtime cohort (cohort_id={cohort_id}) has person property without conditionHash. "- f"All realtime cohorts MUST have conditionHash for person property filters. Property: {prop}"- )-- return self._build_single_condition_query(condition_hash)-- def _collect_person_property_hashes(- self, prop_group: PropertyGroup- ) -> Optional[tuple[list[str], PropertyOperatorType]]:- """Collect all condition hashes from a flat AND/OR of person properties.-- Returns (hashes, operator) if every leaf is a non-negated person property with a- conditionHash, None otherwise (mixed/behavioral/negated conditions fall through to- the multi-subquery path).-- Only inspects one level of nesting: a top-level AND/OR whose children are either- plain Properties or single-property PropertyGroups wrapping a plain Property.- """- operator = prop_group.type- hashes: list[str] = []- for value in prop_group.values:- if isinstance(value, Property):- prop = value- elif len(value.values) == 1 and isinstance(value.values[0], Property):- prop = value.values[0]- else:- # Nested group with multiple or non-Property children → not a flat person-property group.- return None-- # Must be a non-negated person property with a conditionHash- condition_hash = getattr(prop, "conditionHash", None)- if prop.type != "person" or prop.negation or not condition_hash:- return None-- # Merged properties carry multiple hashes- merged = getattr(prop, "_merged_condition_hashes", None)- if merged:- # A merged child encodes its own AND/OR across its hashes. Flattening them into- # the parent's single threshold only preserves semantics when the child's boolean- # type matches the top-level operator (e.g. an OR-merged child under a top-level- # AND would wrongly require ALL its hashes). Otherwise defer to the multi-subquery- # path, which expresses the nested boolean correctly.- if len(merged) > 1:- child_is_or = getattr(prop, "_is_or_group", False)- parent_is_or = operator == PropertyOperatorType.OR- if child_is_or != parent_is_or:- return None- hashes.extend(merged)- else:- hashes.append(condition_hash)-- if not hashes:- return None- return hashes, operator-- def _leaf_having_expr(self, prop: Property, all_hashes: list[str]) -> Optional[ast.Expr]:- """Build the HAVING predicate for one person-property leaf, over the single-scan rows.-- The inner scan emits one row per (person, condition) with `latest_matches`, so in the- outer GROUP BY person_id a leaf is "did this person's latest row(s) for these hashes- match?":- - single hash / OR-merged → maxIf(latest_matches, condition IN hashes) = 1 (any matched)- - AND-merged → countIf(latest_matches = 1 AND condition IN hashes) = N (all matched)-- Returns None for anything that isn't a non-negated person property with a conditionHash- (behavioral, dynamic-cohort, negated, …), so the caller falls through to the parent path.- """- if prop.type != "person" or prop.negation:- return None- condition_hash = getattr(prop, "conditionHash", None)- if not condition_hash:- return None-- merged = getattr(prop, "_merged_condition_hashes", None)- hashes = self._deduplicate_hashes(merged) if merged else [condition_hash]- all_hashes.extend(hashes)- hashes_tuple = ast.Tuple(exprs=[ast.Constant(value=h) for h in hashes])-- # A single hash or an OR-merged leaf matches if ANY of its hashes is the person's latest 1.- if len(hashes) == 1 or getattr(prop, "_is_or_group", False):- return parse_expr("maxIf(latest_matches, condition IN {hashes}) = 1", {"hashes": hashes_tuple})- # An AND-merged leaf matches only if ALL of its hashes are the person's latest 1.- return parse_expr(- "countIf(latest_matches = 1 AND condition IN {hashes}) = {n}",- {"hashes": hashes_tuple, "n": ast.Constant(value=len(hashes))},- )-- def _build_person_property_having(self, prop_group: PropertyGroup, all_hashes: list[str]) -> Optional[ast.Expr]:- """Recursively turn a nested AND/OR of person properties into one HAVING boolean expr.-- Every leaf hash is appended to `all_hashes` so the caller can scope the scan's- `condition IN (...)` filter. Returns None if any leaf is unsupported, so the whole cohort- falls through to the parent's multi-subquery path.- """- operator = prop_group.type- if operator not in (PropertyOperatorType.AND, PropertyOperatorType.OR):- return None-- child_exprs: list[ast.Expr] = []- for value in prop_group.values:- if isinstance(value, PropertyGroup):- child = self._build_person_property_having(value, all_hashes)- else:- child = self._leaf_having_expr(value, all_hashes)- if child is None:- return None- child_exprs.append(child)-- if not child_exprs:- return None- if len(child_exprs) == 1:- return child_exprs[0]- return ast.And(exprs=child_exprs) if operator == PropertyOperatorType.AND else ast.Or(exprs=child_exprs)-- def _build_boolean_tree_query(self, prop_group: PropertyGroup) -> Optional[ast.SelectQuery]:- """One scan for an arbitrarily nested AND/OR of person properties.-- Generalises the flat single-scan: instead of INTERSECT/UNION DISTINCT-ing N person sets- (which materialises N intermediate sets and OOMs on large cohorts), it reads the table- once and evaluates the whole boolean expression per person in the HAVING.- """- all_hashes: list[str] = []- having = self._build_person_property_having(prop_group, all_hashes)- if having is None or not all_hashes:- return None-- deduplicated = self._deduplicate_hashes(all_hashes)- return self._single_scan_membership_query(deduplicated, having)-- def _get_conditions(self) -> ast.SelectQuery | ast.SelectSetQuery:- """Override to emit a single-scan query when all conditions are person properties.-- For cohorts backed entirely by precalculated_person_properties, the parent would produce- N separate subqueries joined by INTERSECT/UNION DISTINCT. Each subquery reads the full- table and the set operations materialise large intermediate person sets — a common source- of OOMs for large cohorts. We instead read the table once.-- Two shapes qualify, tried in order:- 1. Flat AND/OR of leaves → count matched conditions per person (HAVING countIf >= N).- 2. Arbitrarily nested AND/OR of leaves → evaluate the boolean tree per person in the- HAVING (maxIf/countIf leaves combined with AND/OR).-- Shape 1 is a strict subset of shape 2 (the tree would produce an equivalent AND/OR of- per-leaf maxIf predicates), but it's kept as a faster path: one `countIf >= N` over the- whole group is cheaper than N separate `maxIf` leaves.-- Cohorts with any non-person leaf (behavioral, dynamic-cohort, static-cohort) or a negated- person property fall through to the parent's multi-subquery path unchanged.- """- if self.property_groups is not None:- result = self._collect_person_property_hashes(self.property_groups)- if result is not None:- hashes, operator = result- return self._build_count_match_query(hashes, operator)- tree_query = self._build_boolean_tree_query(self.property_groups)- if tree_query is not None:- return tree_query- return super()._get_conditions()-- def get_static_cohort_condition(self, prop: Property) -> ast.SelectQuery:- """- Realtime cohorts do not support static cohorts.- Static cohorts use manually uploaded CSV data and are not compatible with realtime calculation.- """- raise ValueError(- "Realtime cohorts do not support static cohort filters. "- "Only dynamic cohorts and behavioral filters are supported for realtime calculation."- )-- def get_person_metadata_condition(self, prop: Property) -> ast.SelectQuery:- # TODO: realtime cohorts read from precalculated_person_properties keyed by conditionHash, which only- # carries values from the persons properties JSON blob — top-level columns like created_at are not- # exposed. Extend the realtime backfill/consumer if/when there's demand.- raise ValueError(- "Realtime cohorts do not support 'person_metadata' filters. "- "Use a non-realtime cohort to filter on top-level person columns like created_at."- )-- def get_performed_event_sequence(self, prop: Property) -> ast.SelectQuery:- """- Realtime cohorts do not support performed_event_sequence.- Only performed_event and performed_event_multiple are supported by build_behavioral_event_expr.- """- raise ValueError(- "Realtime cohorts do not support 'performed_event_sequence'. "- "Only 'performed_event' and 'performed_event_multiple' are supported."- )-- def get_stopped_performing_event(self, prop: Property) -> ast.SelectSetQuery:- """- Realtime cohorts do not support stopped_performing_event.- Only performed_event and performed_event_multiple are supported by build_behavioral_event_expr.- """- raise ValueError(- "Realtime cohorts do not support 'stopped_performing_event'. "- "Only 'performed_event' and 'performed_event_multiple' are supported."- )-- def get_restarted_performing_event(self, prop: Property) -> ast.SelectSetQuery:- """- Realtime cohorts do not support restarted_performing_event.- Only performed_event and performed_event_multiple are supported by build_behavioral_event_expr.- """- raise ValueError(- "Realtime cohorts do not support 'restarted_performing_event'. "- "Only 'performed_event' and 'performed_event_multiple' are supported."- )-- def get_performed_event_regularly(self, prop: Property) -> ast.SelectQuery:- """- Realtime cohorts do not support performed_event_regularly.- Only performed_event and performed_event_multiple are supported by build_behavioral_event_expr.- """- raise ValueError(- "Realtime cohorts do not support 'performed_event_regularly'. "- "Only 'performed_event' and 'performed_event_multiple' are supported."- )diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.pyindex 0682ca017576..e8fae4322540 100644--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py@@ -1,47 +1,16 @@-import datetime as dtfrom datetime import datetimefrom typing import cast-from uuid import UUID, uuid4from zoneinfo import ZoneInfofrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_eventsfrom unittest.mock import MagicMock, patch-from parameterized import parameterized--from posthog.hogql.constants import LimitContext-from posthog.hogql.context import HogQLContext-from posthog.hogql.printer import prepare_and_print_ast-from posthog.clickhouse.client import sync_execute-from posthog.constants import PropertyOperatorType-from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery, HogQLRealtimeCohortQuery-from posthog.models.property import Property, PropertyGroup+from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQueryfrom products.cohorts.backend.models.cohort import Cohort-# Local single-node mirror of the production precalculated_person_properties table (which is-# sharded/distributed and absent from the test ClickHouse schema). Created per execution test.-_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL = """-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 = 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."""@@ -530,8 +499,6 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):)cohort.calculate_people_ch(pending_version=0)- from posthog.clickhouse.client.execute import sync_execute-rows = sync_execute("SELECT person_id FROM cohortpeople WHERE cohort_id = %(cohort_id)s AND team_id = %(team_id)s ""GROUP BY person_id, cohort_id, team_id, version HAVING sum(sign) > 0",@@ -655,8 +622,6 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):)cohort.calculate_people_ch(pending_version=0)- from posthog.clickhouse.client.execute import sync_execute-rows = sync_execute("SELECT person_id FROM cohortpeople WHERE cohort_id = %(cohort_id)s AND team_id = %(team_id)s ""GROUP BY person_id, cohort_id, team_id, version HAVING sum(sign) > 0",@@ -666,36 +631,6 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):self.assertIn(str(old_person.uuid), member_ids)self.assertNotIn(str(new_person.uuid), member_ids)- def test_person_metadata_realtime_cohort_raises_error(self) -> None:- cohort = Cohort.objects.create(- team=self.team,- name="created after 2024 realtime",- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "created_at",- "type": "person_metadata",- "value": "2024-06-01",- "operator": "is_date_after",- "conditionHash": "test_pm_hash",- }- ],- }- ],- }- },- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)- with self.assertRaises(ValueError) as ctx:- hogql_query.query_str("clickhouse")- self.assertIn("person_metadata", str(ctx.exception))-def test_static_cohort_condition_rejects_cross_project_cohort(self) -> None:from posthog.models.organization import Organization@@ -722,2126 +657,3 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):hogql_query = HogQLCohortQuery(cohort=cohort)with self.assertRaises(Cohort.DoesNotExist):hogql_query.query_str("clickhouse")---class TestHogQLRealtimeCohortQuery(ClickhouseTestMixin, APIBaseTest):- """Tests for HogQLRealtimeCohortQuery which uses precalculated_events for behavioral filters."""-- def test_person_property_query(self) -> None:- """- Test that person property filters work correctly in realtime cohorts.- """- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "@posthog.com",- "negation": False,- "operator": "icontains",- "conditionHash": "test123abc456",- "bytecode": ["_H", 1, 32, "email", 32, "@posthog.com", 2, "icontains", 2],- }- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Realtime Person Property", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)- query_str = hogql_query.query_str("clickhouse")-- # Should query precalculated_person_properties table for person properties- self.assertIn("precalculated_person_properties", query_str)- # Should have condition hash filter- self.assertIn("condition", query_str)-- def test_behavioral_performed_event_pageview(self) -> None:- """- Test that a simple behavioral performed_event filter works with conditionHash.- """- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$pageview",- "type": "behavioral",- "value": "performed_event",- "negation": False,- "event_type": "events",- "time_value": 7,- "time_interval": "day",- "conditionHash": "abc123def456",- }- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Behavioral Pageview", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)-- query_str = hogql_query.query_str("clickhouse")-- # Should query precalculated_events table- self.assertIn("precalculated_events", query_str)- # Should have condition field (conditionHash is parameterized)- self.assertIn("precalculated_events.condition", query_str)- # Should use person_id directly from precalculated_events- self.assertIn("person_id", query_str)- # Should have date filtering with toDate- self.assertIn("toDate", query_str)-- def test_cohort_membership_in_cohort_direct(self) -> None:- """- Test that get_dynamic_cohort_condition generates correct query for cohort membership.- """- from posthog.models.property import Property-- # Create a target cohort- target_cohort = Cohort.objects.create(- team=self.team, name="Target Cohort", filters={"properties": {"type": "AND", "values": []}}- )-- # Create a simple cohort for the query object- cohort = Cohort.objects.create(- team=self.team, name="Test Cohort", filters={"properties": {"type": "AND", "values": []}}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)-- # Create a dynamic-cohort property (this is what unwrap_cohort would create)- prop = Property(type="dynamic-cohort", key="id", value=target_cohort.id, negation=False)-- # Call get_dynamic_cohort_condition directly- query_ast = hogql_query.get_dynamic_cohort_condition(prop)-- # Print the AST to string- from posthog.hogql.printer import prepare_and_print_ast-- query_str = prepare_and_print_ast(query_ast, hogql_query.hogql_context, "clickhouse", pretty=True)[0]-- # Should query cohort_membership table- self.assertIn("cohort_membership", query_str)- # Should have cohort_id filter- self.assertIn("cohort_membership.cohort_id", query_str)- # Should check status field and use argMax for latest status- self.assertIn("cohort_membership.status", query_str)- self.assertIn("argmax", query_str.lower())- # Should filter by person_id and use HAVING clause for status check- self.assertIn("person_id", query_str.lower())- self.assertIn("having", query_str.lower())-- def test_cohort_membership_not_in_cohort_direct(self) -> None:- """- Test that negated cohort membership uses EXCEPT to exclude cohort members.- """- from posthog.hogql.printer import prepare_and_print_ast-- from posthog.models.property import Property-- # Create a target cohort- target_cohort = Cohort.objects.create(- team=self.team, name="Target Cohort", filters={"properties": {"type": "AND", "values": []}}- )-- # Create a simple cohort for the query object- cohort = Cohort.objects.create(- team=self.team, name="Test Cohort", filters={"properties": {"type": "AND", "values": []}}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)-- # Create a negated dynamic-cohort property- prop = Property(type="dynamic-cohort", key="id", value=target_cohort.id, negation=True)-- # When negation=True, the property is handled through build_conditions with EXCEPT- # We need to test through _get_condition_for_property- query_ast = hogql_query._get_condition_for_property(prop)-- # Print the AST to string- query_str = prepare_and_print_ast(query_ast, hogql_query.hogql_context, "clickhouse", pretty=True)[0]-- # Should still query cohort_membership table- self.assertIn("cohort_membership", query_str)- # Should have cohort_id filter- self.assertIn("cohort_membership.cohort_id", query_str)-- def test_behavioral_performed_event_multiple(self) -> None:- """- Test that performed_event_multiple queries precalculated_events with count aggregation.- """- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$pageview",- "type": "behavioral",- "value": "performed_event_multiple",- "negation": False,- "operator": "gte",- "event_type": "events",- "operator_value": 5,- "time_value": 30,- "time_interval": "day",- "conditionHash": "xyz789abc123",- }- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Behavioral Multiple", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)- query_str = hogql_query.query_str("clickhouse")-- # Should query precalculated_events- self.assertIn("precalculated_events", query_str)- # Should have count aggregation- self.assertIn("count()", query_str)- # Should have HAVING clause for count filtering- self.assertIn("HAVING", query_str)- # Should use person_id directly from precalculated_events- self.assertIn("person_id", query_str)- # Should group by person_id- self.assertIn("GROUP BY", query_str)-- def test_behavioral_performed_event_multiple_times_alias_does_not_raise(self) -> None:- """Regression: `performed_event_multiple_times` (the realtime-cohort builder's alias for- `performed_event_multiple`) used to leave `Property.value` as the raw alias string, so- this dispatch's `prop.value == "performed_event_multiple"` check fell through to- `else: raise ValueError`."""- cohort = Cohort.objects.create(- team=self.team, name="Test Cohort", filters={"properties": {"type": "AND", "values": []}}- )- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)-- prop = Property(- key="$pageview",- type="behavioral",- value="performed_event_multiple_times",- event_type="events",- operator="gte",- operator_value=5,- time_value=30,- time_interval="day",- conditionHash="xyz789abc123",- )-- query_ast = hogql_query._get_condition_for_property(prop)- query_str = prepare_and_print_ast(query_ast, hogql_query.hogql_context, "clickhouse", pretty=True)[0]-- self.assertIn("precalculated_events", query_str)-- def test_behavioral_performed_event_with_date_range(self) -> None:- """performed_event with explicit_datetime + explicit_datetime_to bounds both ends of the window."""- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$pageview",- "type": "behavioral",- "value": "performed_event",- "negation": False,- "event_type": "events",- "explicit_datetime": "-30d",- "explicit_datetime_to": "-7d",- "conditionHash": "range_hash_1",- }- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Behavioral Range", filters={"properties": cohort_filters}- )- query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse")-- self.assertIn("precalculated_events", query_str)- # Both sides of the window should be emitted. HogQL prints `>=`/`<=` as- # `greaterOrEquals(...)` / `lessOrEquals(...)` function calls for ClickHouse.- self.assertEqual(query_str.count("toDate("), 2)- self.assertIn("greaterOrEquals", query_str)- self.assertIn("lessOrEquals", query_str)-- def test_behavioral_performed_event_multiple_with_date_range(self) -> None:- """performed_event_multiple with a bounded window still aggregates counts."""- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$pageview",- "type": "behavioral",- "value": "performed_event_multiple",- "negation": False,- "operator": "gte",- "event_type": "events",- "operator_value": 3,- "explicit_datetime": "-30d",- "explicit_datetime_to": "-7d",- "conditionHash": "range_hash_2",- }- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Behavioral Multiple Range", filters={"properties": cohort_filters}- )- query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse")-- self.assertIn("precalculated_events", query_str)- self.assertIn("count()", query_str)- self.assertIn("HAVING", query_str)- self.assertEqual(query_str.count("toDate("), 2)-- def test_behavioral_performed_event_without_date_range_omits_upper_bound(self) -> None:- """When only explicit_datetime is set, only the lower bound shows up."""- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$pageview",- "type": "behavioral",- "value": "performed_event",- "negation": False,- "event_type": "events",- "explicit_datetime": "-30d",- "conditionHash": "range_hash_3",- }- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Behavioral Lower Bound", filters={"properties": cohort_filters}- )- query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse")-- self.assertEqual(query_str.count("toDate("), 1)- self.assertNotIn("lessOrEquals", query_str)-- def test_static_cohort_raises_error(self) -> None:- """- Test that static cohort filters raise an error for realtime cohorts.- Static cohorts are not supported in realtime calculation.- """- # First create a static cohort- static_cohort = Cohort.objects.create(- team=self.team, name="Static Cohort", is_static=True, is_calculating=False- )-- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [{"key": "id", "type": "static-cohort", "value": static_cohort.id, "negation": False}],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Static Cohort Error", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)-- # Should raise ValueError when trying to generate query- with self.assertRaises(ValueError) as context:- hogql_query.query_str("clickhouse")-- self.assertIn("static cohort", str(context.exception).lower())-- def test_or_group_with_same_key_operator_merges(self) -> None:- """- Test that OR groups with same key and operator are merged with OR semantics.-- For example: email contains "@gmail.com" OR email contains "@yahoo.com"- This should find users whose email contains ANY of these strings (at least one).-- Also tests that properties with different operators or keys are NOT merged.- """- cohort_filters = {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- # These 3 should merge (same key, operator, not negated)- {- "key": "email",- "type": "person",- "value": "@gmail.com",- "bytecode": [- "_H",- 1,- 32,- "%@gmail.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "a5c1c77ac5bfac89",- },- {- "key": "email",- "type": "person",- "value": ["@yahoo.com"],- "bytecode": [- "_H",- 1,- 32,- "%@yahoo.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "102924b91ae29fc8",- },- {- "key": "email",- "type": "person",- "value": "@live.com",- "bytecode": [- "_H",- 1,- 32,- "%@live.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "e849069d7a368305",- },- # Different operator - should NOT merge- {- "key": "email",- "type": "person",- "value": "[email protected]",- "bytecode": [- "_H",- 1,- 32,- "[email protected]",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 15,- ],- "negation": False,- "operator": "exact",- "conditionHash": "different_operator_hash",- },- # Different operator (negated version) - should NOT merge- {- "key": "email",- "type": "person",- "value": "@hotmail.com",- "bytecode": [- "_H",- 1,- 32,- "%@hotmail.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "not_icontains",- "conditionHash": "271b98d7d31ca2ce",- },- # Different key - should NOT merge- {- "key": "name",- "type": "person",- "value": "John",- "bytecode": [- "_H",- 1,- 32,- "%John%",- 32,- "name",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "different_key_hash",- },- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test OR Group Merge", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)- query_str = hogql_query.query_str("clickhouse")-- # All 6 conditions (3 mergeable + 3 non-mergeable) collapse into one scan with a- # single IN clause and HAVING countIf >= 1 (OR semantics).- self.assertIn("in(precalculated_person_properties.condition,", query_str.lower())- self.assertNotIn("UNION DISTINCT", query_str)- self.assertNotIn("INTERSECT DISTINCT", query_str)- # OR threshold: at least one condition must match- self.assertIn("countif(", query_str.lower())- self.assertIn("greaterOrEquals", query_str)-- def test_or_group_with_nested_single_property_groups_merges(self) -> None:- """- Test that nested OR groups with single properties get merged.-- For example:- OR:- - Group 1: [email contains "@gmail.com"]- - Group 2: [email contains "@yahoo.com"]- - Group 3: [email contains "@live.com"]-- These should be unwrapped and merged into a single query.- """- cohort_filters = {- "type": "OR",- "values": [- # Each of these is a separate OR group with a single property- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "@gmail.com",- "bytecode": [- "_H",- 1,- 32,- "%@gmail.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "nested1_gmail",- },- ],- },- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "@yahoo.com",- "bytecode": [- "_H",- 1,- 32,- "%@yahoo.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "nested2_yahoo",- },- ],- },- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "@live.com",- "bytecode": [- "_H",- 1,- 32,- "%@live.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "nested3_live",- },- ],- },- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Nested OR Groups Merge", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)- query_str = hogql_query.query_str("clickhouse")-- # All 3 nested single-property groups should be unwrapped and merged- # Should have exactly 1 IN clause for all 3 conditions- in_clause_count = query_str.lower().count("in(precalculated_person_properties.condition,")- self.assertEqual(in_clause_count, 1, "Should have exactly 1 IN clause for merged conditions")-- # Should have no single condition checks (all merged)- single_condition_count = query_str.lower().count("equals(precalculated_person_properties.condition,")- self.assertEqual(single_condition_count, 0, "Should have no single condition checks (all merged)")-- # Should NOT use UNION DISTINCT since all properties are merged- self.assertNotIn("UNION DISTINCT", query_str)-- def test_and_group_with_same_key_operator_merges(self) -> None:- """- Test that AND groups with same key and operator are merged with AND semantics.-- For example: email contains "@gmail" AND email contains ".com"- This should find users whose email contains ALL of these strings (all conditions must match).- """- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "@gmail",- "bytecode": [- "_H",- 1,- 32,- "%@gmail%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "hash1_gmail",- },- {- "key": "email",- "type": "person",- "value": ".com",- "bytecode": [- "_H",- 1,- 32,- "%.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "hash2_dotcom",- },- {- "key": "email",- "type": "person",- "value": "test",- "bytecode": [- "_H",- 1,- 32,- "%test%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "hash3_test",- },- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test AND Group Merge", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)- query_str = hogql_query.query_str("clickhouse")-- # Should use IN clause to fetch all conditions at once- self.assertIn("in(precalculated_person_properties.condition,", query_str.lower())- # AND semantics: all 3 conditions must match. Pin the full predicate so the threshold- # (3, not 1) is verified rather than a substring that any threshold would satisfy.- self.assertIn("greaterorequals(countif(equals(latest_matches, 1)), 3)", query_str.lower())- # Should NOT use UNION/INTERSECT DISTINCT since properties collapse into one scan- self.assertNotIn("UNION DISTINCT", query_str)- self.assertNotIn("INTERSECT DISTINCT", query_str)-- def test_sibling_single_property_groups_under_or_merge(self) -> None:- """- Test that sibling single-property groups under a top-level OR are merged together- when they have the same key and operator, including already-merged groups.-- For example:- OR:- - AND: [email icontains @gmail.com, name icontains John] # can't merge (different keys)- - OR: [email icontains yahoo.com] # single property- - OR: [email icontains @protonmail.com, email icontains @live.com] # already merged within group-- The last two groups should ALL be merged together (yahoo + protonmail + live = 3 hashes).- """- cohort_filters = {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "@gmail.com",- "bytecode": [- "_H",- 1,- 32,- "%@gmail.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "hash1_gmail",- },- {- "key": "name",- "type": "person",- "value": "John",- "bytecode": [- "_H",- 1,- 32,- "%John%",- 32,- "name",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "hash2_john",- },- ],- },- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "yahoo.com",- "bytecode": [- "_H",- 1,- 32,- "%yahoo.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "hash3_yahoo",- },- ],- },- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "@protonmail.com",- "bytecode": [- "_H",- 1,- 32,- "%@protonmail.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "hash4_protonmail",- },- {- "key": "email",- "type": "person",- "value": "@live.com",- "bytecode": [- "_H",- 1,- 32,- "%@live.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "hash5_live",- },- ],- },- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Sibling Single Property Groups Merge", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)- query_str = hogql_query.query_str("clickhouse")-- # The whole nested boolean is now evaluated in one scan's HAVING — no set operations.- self.assertNotIn("UNION DISTINCT", query_str)- self.assertNotIn("INTERSECT DISTINCT", query_str)- self.assertIn("maxif(latest_matches", query_str.lower())-- # The 3 sibling email properties (yahoo + protonmail + live) still merge into one OR leaf,- # so its IN tuple has exactly 3 values.- tuple_pattern = r"tuple\(%\(hogql_val_\d+\)s,\s*%\(hogql_val_\d+\)s,\s*%\(hogql_val_\d+\)s\)"- self.assertRegex(query_str, tuple_pattern, "merged email leaf should be a 3-value IN tuple")-- def test_properties_without_condition_hash_are_not_merged(self) -> None:- """- Test that properties without conditionHash are not merged and don't cause empty IN clauses.-- This tests the edge case where multiple properties have the same key and operator- but none of them have conditionHash set. The validation should prevent creating- a merged property with empty hashes.- """- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "@gmail.com",- "negation": False,- "operator": "icontains",- # Note: No conditionHash- },- {- "key": "email",- "type": "person",- "value": "@yahoo.com",- "negation": False,- "operator": "icontains",- # Note: No conditionHash- },- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Properties Without Hash", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)-- # Should raise ValueError because realtime cohorts require conditionHash- with self.assertRaises(ValueError) as context:- hogql_query.query_str("clickhouse")-- self.assertIn("conditionhash", str(context.exception).lower())-- def test_merged_property_with_empty_hashes_raises_error(self) -> None:- """- Test that attempting to query a merged property with empty hashes raises a clear error.-- This tests the defensive validation in get_person_condition that prevents- generating invalid SQL with empty IN clauses.- """- from posthog.models.property import Property-- cohort = Cohort.objects.create(- team=self.team, name="Test Empty Hashes", filters={"properties": {"type": "AND", "values": []}}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)-- # Create a property with empty _merged_condition_hashes (simulating a bug)- prop = Property(- key="email",- type="person",- value="@gmail.com",- negation=False,- operator="icontains",- conditionHash="test_hash",- )- # Simulate a bug where _merged_condition_hashes is set to empty list- prop._merged_condition_hashes = [] # type: ignore[attr-defined]- prop._is_or_group = True # type: ignore[attr-defined]-- # Should raise ValueError about empty condition hashes- with self.assertRaises(ValueError) as context:- hogql_query.get_person_condition(prop)-- error_msg = str(context.exception).lower()- self.assertIn("empty condition hashes", error_msg)- self.assertIn("invalid sql", error_msg)-- def test_create_merged_property_with_empty_hashes_raises_error(self) -> None:- """- Test that _create_merged_property raises an error when called with empty unique_hashes.-- This ensures the method is defensive and validates its inputs.- """- from posthog.models.property import Property-- cohort = Cohort.objects.create(- team=self.team, name="Test Create Merged Property", filters={"properties": {"type": "AND", "values": []}}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)-- template = Property(- key="email",- type="person",- value="@gmail.com",- negation=False,- operator="icontains",- conditionHash="test_hash",- )-- # Should raise ValueError when unique_hashes is empty- with self.assertRaises(ValueError) as context:- hogql_query._create_merged_property(template, [], is_or_group=True)-- error_msg = str(context.exception).lower()- self.assertIn("empty unique_hashes", error_msg)-- def test_duplicate_condition_hashes_deduplicated_correctly(self) -> None:- """- Test that duplicate condition hashes are deduplicated when merging properties.-- This tests the edge case where a user accidentally adds the same filter multiple times- (e.g., "email contains @gmail.com" appears twice). The deduplication ensures that- the count matches the distinct conditions in the GROUP BY query.- """- cohort_filters = {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- # Same condition hash appears 3 times (simulating accidental duplicates)- {- "key": "email",- "type": "person",- "value": "@gmail.com",- "bytecode": [- "_H",- 1,- 32,- "%@gmail.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "duplicate_hash_123",- },- {- "key": "email",- "type": "person",- "value": "@gmail.com", # Same filter again- "bytecode": [- "_H",- 1,- 32,- "%@gmail.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "duplicate_hash_123", # Same hash- },- {- "key": "email",- "type": "person",- "value": "@gmail.com", # Same filter third time- "bytecode": [- "_H",- 1,- 32,- "%@gmail.com%",- 32,- "email",- 32,- "properties",- 32,- "person",- 1,- 3,- 2,- "toString",- 1,- 18,- ],- "negation": False,- "operator": "icontains",- "conditionHash": "duplicate_hash_123", # Same hash again- },- ],- }- ],- }-- cohort = Cohort.objects.create(- team=self.team, name="Test Duplicate Hashes", filters={"properties": cohort_filters}- )-- hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)- query_str = hogql_query.query_str("clickhouse")-- # Deduplicated to a single condition → cheaper one-pass query: `condition = hash`- # equality, no IN clause and no cross-condition counting.- self.assertIn("equals(precalculated_person_properties.condition,", query_str.lower())- self.assertNotIn("in(precalculated_person_properties.condition,", query_str.lower())- self.assertNotIn("countif", query_str.lower())-- # Should NOT use INTERSECT since all properties merged into one- self.assertNotIn("INTERSECT DISTINCT", query_str)-- @parameterized.expand(- [- (- # AND of 3 person properties with different keys → single scan, threshold = N (3)- "cross_condition_and",- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "@posthog.com",- "negation": False,- "operator": "icontains",- "conditionHash": "hash_email_001",- },- {- "key": "plan",- "type": "person",- "value": "enterprise",- "negation": False,- "operator": "exact",- "conditionHash": "hash_plan_002",- },- {- "key": "country",- "type": "person",- "value": "US",- "negation": False,- "operator": "exact",- "conditionHash": "hash_country_003",- },- ],- }- ],- },- [- "in(precalculated_person_properties.condition,",- "greaterorequals(countif(equals(latest_matches, 1)), 3)",- ],- ["intersect distinct", "union distinct"],- ),- (- # OR of 2 person properties with different keys → single scan, threshold = 1- "cross_condition_or",- {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "@posthog.com",- "negation": False,- "operator": "icontains",- "conditionHash": "hash_email_or_001",- },- {- "key": "plan",- "type": "person",- "value": "enterprise",- "negation": False,- "operator": "exact",- "conditionHash": "hash_plan_or_002",- },- ],- }- ],- },- [- "in(precalculated_person_properties.condition,",- "greaterorequals(countif(equals(latest_matches, 1)), 1)",- ],- ["intersect distinct", "union distinct"],- ),- (- # Mixed behavioral + person property → falls through to multi-subquery path- "mixed_behavioral_and_person_falls_through",- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$pageview",- "type": "behavioral",- "value": "performed_event",- "negation": False,- "event_type": "events",- "time_value": 7,- "time_interval": "day",- "conditionHash": "behavioral_hash_001",- },- {- "key": "email",- "type": "person",- "value": "@posthog.com",- "negation": False,- "operator": "icontains",- "conditionHash": "person_hash_001",- },- ],- }- ],- },- ["intersect distinct", "precalculated_events", "precalculated_person_properties"],- [],- ),- (- # Single person property → cheaper one-pass query (no cross-condition counting)- "single_property",- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "@posthog.com",- "negation": False,- "operator": "icontains",- "conditionHash": "hash_single_001",- },- ],- }- ],- },- ["equals(argmax(precalculated_person_properties.matches"],- ["intersect distinct", "union distinct", "countif"],- ),- (- # Negated person property → falls through (single-scan must NOT fire)- "negated_person_falls_through",- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "@posthog.com",- "negation": False,- "operator": "icontains",- "conditionHash": "neg_keep_001",- },- {- "key": "name",- "type": "person",- "value": "spam",- "negation": True,- "operator": "icontains",- "conditionHash": "neg_drop_002",- },- ],- }- ],- },- ["precalculated_person_properties"],- ["greaterorequals(countif(equals(latest_matches, 1))"],- ),- (- # (X OR Y) AND (A OR B): nested OR groups under a top-level AND. The boolean-tree- # single scan expresses this as `maxIf(...) = 1 AND maxIf(...) = 1`, NOT a flat- # `>= 4` threshold (which would wrongly require all four).- "nested_or_under_and_single_scan",- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "@x.com",- "negation": False,- "operator": "icontains",- "conditionHash": "nest_hx_001",- },- {- "key": "email",- "type": "person",- "value": "@y.com",- "negation": False,- "operator": "icontains",- "conditionHash": "nest_hy_002",- },- ],- },- {- "type": "OR",- "values": [- {- "key": "plan",- "type": "person",- "value": "A",- "negation": False,- "operator": "exact",- "conditionHash": "nest_ha_003",- },- {- "key": "plan",- "type": "person",- "value": "B",- "negation": False,- "operator": "exact",- "conditionHash": "nest_hb_004",- },- ],- },- ],- }- ],- },- ["maxif(latest_matches"],- ["intersect distinct", "union distinct"],- ),- (- # Deeply nested AND-of-AND with different-key (non-mergeable) props → single scan- "deeply_nested_single_scan",- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "@x.com",- "negation": False,- "operator": "icontains",- "conditionHash": "deep_001",- },- {- "key": "plan",- "type": "person",- "value": "A",- "negation": False,- "operator": "exact",- "conditionHash": "deep_002",- },- ],- },- {- "type": "AND",- "values": [- {- "key": "country",- "type": "person",- "value": "US",- "negation": False,- "operator": "exact",- "conditionHash": "deep_003",- },- {- "key": "role",- "type": "person",- "value": "admin",- "negation": False,- "operator": "exact",- "conditionHash": "deep_004",- },- ],- },- ],- }- ],- },- ["maxif(latest_matches"],- ["intersect distinct", "union distinct"],- ),- ]- )- def test_single_scan_optimization(- self,- name: str,- cohort_filters: dict,- expected_present: list[str],- expected_absent: list[str],- ) -> None:- cohort = Cohort.objects.create(team=self.team, name=f"Test {name}", filters={"properties": cohort_filters})- query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse").lower()-- for substring in expected_present:- self.assertIn(substring, query_str)- for substring in expected_absent:- self.assertNotIn(substring, query_str)-- def _seed_precalculated_person_properties(self, rows: list[tuple[UUID, str, bool]]) -> None:- """Seed (person_id, condition, matches) rows for the current team."""- timestamp = dt.datetime(2026, 1, 1)- payload = [- (self.team.pk, str(person_id), str(person_id), condition, 1 if matches else 0, "test", timestamp, offset)- for offset, (person_id, condition, matches) in enumerate(rows)- ]- sync_execute(- "INSERT INTO precalculated_person_properties "- "(team_id, distinct_id, person_id, condition, matches, source, _timestamp, _offset) VALUES",- payload,- )-- def _realtime_cohort_members(self, cohort: Cohort) -> set[str]:- """Execute a realtime cohort's current-members query and return the matched person_ids."""- query = HogQLRealtimeCohortQuery(cohort=cohort).get_query()- context = HogQLContext(- team_id=self.team.pk, enable_select_queries=True, limit_context=LimitContext.COHORT_CALCULATION- )- sql, _ = prepare_and_print_ast(query, context, "clickhouse")- return {str(row[0]) for row in sync_execute(sql, context.values)}-- def test_single_scan_membership_matches_boolean_semantics(self) -> None:- """Execute the single-scan query against seeded data and assert who actually matches.-- String assertions can't catch a wrong argMax pick, a broken countIf, or an AND/OR- threshold flip — all would produce valid SQL and the wrong cohort. This seeds rows and- checks membership directly.- """- sync_execute(_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL)- sync_execute("TRUNCATE TABLE precalculated_person_properties")- try:- and_all, and_two = uuid4(), uuid4()- or_one, or_none = uuid4(), uuid4()- self._seed_precalculated_person_properties(- [- # AND cohort (hashes A, B, C): all three vs only two- (and_all, "exec_A", True),- (and_all, "exec_B", True),- (and_all, "exec_C", True),- (and_two, "exec_A", True),- (and_two, "exec_B", True),- (and_two, "exec_C", False),- # OR cohort (hashes D, E): one of two vs none- (or_one, "exec_D", True),- (or_one, "exec_E", False),- (or_none, "exec_D", False),- (or_none, "exec_E", False),- ]- )-- and_cohort = Cohort.objects.create(- team=self.team,- name="exec AND",- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "a",- "type": "person",- "value": "x",- "negation": False,- "operator": "exact",- "conditionHash": "exec_A",- },- {- "key": "b",- "type": "person",- "value": "y",- "negation": False,- "operator": "exact",- "conditionHash": "exec_B",- },- {- "key": "c",- "type": "person",- "value": "z",- "negation": False,- "operator": "exact",- "conditionHash": "exec_C",- },- ],- }- ],- }- },- )- and_members = self._realtime_cohort_members(and_cohort)- self.assertIn(str(and_all), and_members) # matched all 3- self.assertNotIn(str(and_two), and_members) # matched only 2 of 3-- or_cohort = Cohort.objects.create(- team=self.team,- name="exec OR",- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "d",- "type": "person",- "value": "x",- "negation": False,- "operator": "exact",- "conditionHash": "exec_D",- },- {- "key": "e",- "type": "person",- "value": "y",- "negation": False,- "operator": "exact",- "conditionHash": "exec_E",- },- ],- }- ],- }- },- )- or_members = self._realtime_cohort_members(or_cohort)- self.assertIn(str(or_one), or_members) # matched 1 of 2- self.assertNotIn(str(or_none), or_members) # matched neither- finally:- sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")-- def test_single_scan_argmax_latest_write_wins(self) -> None:- """argMax picks the row with the highest (_timestamp, _offset), so the latest write wins.-- Seeds two rows per (person, condition): an earlier row with one matches value and a later row- with the opposite. Asserts membership reflects the latest row, not the earlier one.- The helper assigns _offset via enumerate, so a later list entry beats an earlier one.- """- sync_execute(_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL)- sync_execute("TRUNCATE TABLE precalculated_person_properties")- try:- flipped_out, flipped_in = uuid4(), uuid4()- self._seed_precalculated_person_properties(- [- # flipped_out: early True then late False → excluded- (flipped_out, "exec_F", True),- (flipped_out, "exec_F", False),- # flipped_in: early False then late True → included- (flipped_in, "exec_F", False),- (flipped_in, "exec_F", True),- ]- )-- cohort = Cohort.objects.create(- team=self.team,- name="argmax flip",- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "f",- "type": "person",- "value": "x",- "negation": False,- "operator": "exact",- "conditionHash": "exec_F",- }- ],- }- ],- }- },- )- members = self._realtime_cohort_members(cohort)- self.assertNotIn(str(flipped_out), members) # latest write was False- self.assertIn(str(flipped_in), members) # latest write was True- 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)`.-- This shape used to fall through to the INTERSECT/UNION DISTINCT path (the OOM source); the- boolean-tree single scan must return the same person set without those set operations.- """- sync_execute(_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL)- sync_execute("TRUNCATE TABLE precalculated_person_properties")- try:- ab, cd, c_only, a_only = uuid4(), uuid4(), uuid4(), uuid4()- self._seed_precalculated_person_properties(- [- (ab, "exec_A", True),- (ab, "exec_B", True), # matches first branch- (cd, "exec_C", True),- (cd, "exec_D", True), # matches second branch- (c_only, "exec_C", True), # half of second branch only- (a_only, "exec_A", True), # half of first branch only- ]- )-- def leaf(key: str, condition_hash: str) -> dict:- return {- "key": key,- "type": "person",- "value": "x",- "negation": False,- "operator": "exact",- "conditionHash": condition_hash,- }-- cohort = Cohort.objects.create(- team=self.team,- name="nested",- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {"type": "AND", "values": [leaf("k1", "exec_A"), leaf("k2", "exec_B")]},- {"type": "AND", "values": [leaf("k3", "exec_C"), leaf("k4", "exec_D")]},- ],- }- ],- }- },- )- query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse")- self.assertNotIn("INTERSECT DISTINCT", query_str)- self.assertNotIn("UNION DISTINCT", query_str)-- members = self._realtime_cohort_members(cohort)- self.assertIn(str(ab), members) # A AND B- self.assertIn(str(cd), members) # C AND D- self.assertNotIn(str(c_only), members) # C without D- self.assertNotIn(str(a_only), members) # A without B- finally:- sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")-- def test_nested_boolean_single_scan_and_merged_leaf_membership(self) -> None:- """Exercise the AND-merged leaf (countIf(...) = N) inside the boolean tree.-- `(email~@gmail AND email~.com) AND plan` nested under a top-level OR: the same-key email- pair merges into one AND-merged leaf, which the tree must render as- `countIf(latest_matches = 1 AND condition IN (g, c)) = 2` — a person matching only one of- the two merged hashes must be excluded.- """-- def leaf(key: str, value: str, operator: str, condition_hash: str) -> dict:- return {- "key": key,- "type": "person",- "value": value,- "negation": False,- "operator": operator,- "conditionHash": condition_hash,- }-- sync_execute(_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL)- sync_execute("TRUNCATE TABLE precalculated_person_properties")- try:- both, one_only, country_only = uuid4(), uuid4(), uuid4()- self._seed_precalculated_person_properties(- [- (both, "m_g", True),- (both, "m_c", True),- (both, "plan_x", True), # matches the AND-merged email pair + plan- (one_only, "m_g", True),- (one_only, "m_c", False),- (one_only, "plan_x", True), # missed one of the merged hashes- (country_only, "country_y", True), # matches the other OR branch- ]- )- cohort = Cohort.objects.create(- team=self.team,- name="and-merged",- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- leaf("email", "@gmail", "icontains", "m_g"),- leaf("email", ".com", "icontains", "m_c"),- ],- },- {"type": "AND", "values": [leaf("plan", "x", "exact", "plan_x")]},- ],- },- {"type": "AND", "values": [leaf("country", "y", "exact", "country_y")]},- ],- }- ],- }- },- )- query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse").lower()- self.assertNotIn("intersect distinct", query_str)- self.assertNotIn("union distinct", query_str)- self.assertIn("countif(", query_str) # AND-merged leaf renders as countIf(...) = N-- members = self._realtime_cohort_members(cohort)- self.assertIn(str(both), members) # matched both merged hashes + plan- self.assertIn(str(country_only), members) # other OR branch- self.assertNotIn(str(one_only), members) # missed one merged hash → AND-merged leaf fails- finally:- sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")-- def test_nested_negated_leaf_falls_through(self) -> None:- """A negated leaf buried in a nested group must force the parent multi-subquery path.-- The single-scan tree can't express negation, so any nested negated person property must- make `_build_boolean_tree_query` return None and fall through — not silently drop the- negation and produce a wrong cohort.- """- cohort = Cohort.objects.create(- team=self.team,- name="nested-negated",- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "email",- "type": "person",- "value": "@x",- "negation": False,- "operator": "icontains",- "conditionHash": "nn_h1",- }- ],- },- {- "type": "AND",- "values": [- {- "key": "plan",- "type": "person",- "value": "A",- "negation": False,- "operator": "exact",- "conditionHash": "nn_h2",- },- {- "key": "name",- "type": "person",- "value": "spam",- "negation": True,- "operator": "icontains",- "conditionHash": "nn_h3",- },- ],- },- ],- }- ],- }- },- )- query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse").lower()- # Tree path must NOT fire — a negated leaf forces the parent set-operation path.- self.assertNotIn("maxif(latest_matches", query_str)-- def test_nested_or_under_and_membership(self) -> None:- """Execution test for `(X OR Y) AND (A OR B)` — the shape flagged in the parameterized- test as the threshold-flip risk.-- The tree renders it as `maxIf(...X,Y...) = 1 AND maxIf(...A,B...) = 1`, NOT a flat- `countIf >= 4` threshold that would wrongly require all four. A person matching only X- and A (one from each OR branch) must be IN; one matching X and Y but not A or B must be OUT.- """- sync_execute(_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL)- sync_execute("TRUNCATE TABLE precalculated_person_properties")- try:- x_and_a, x_and_y, a_and_b, neither = uuid4(), uuid4(), uuid4(), uuid4()- self._seed_precalculated_person_properties(- [- (x_and_a, "or_X", True),- (x_and_a, "or_A", True), # one from each OR branch → should match- (x_and_y, "or_X", True),- (x_and_y, "or_Y", True), # both from first branch, none from second → no match- (a_and_b, "or_A", True),- (a_and_b, "or_B", True), # both from second branch, none from first → no match- (neither, "or_X", False), # matches nothing- ]- )-- def leaf(key: str, condition_hash: str) -> dict:- return {- "key": key,- "type": "person",- "value": "x",- "negation": False,- "operator": "exact",- "conditionHash": condition_hash,- }-- cohort = Cohort.objects.create(- team=self.team,- name="or-under-and",- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {"type": "OR", "values": [leaf("k1", "or_X"), leaf("k2", "or_Y")]},- {"type": "OR", "values": [leaf("k3", "or_A"), leaf("k4", "or_B")]},- ],- }- ],- }- },- )- query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse")- self.assertNotIn("INTERSECT DISTINCT", query_str)- self.assertNotIn("UNION DISTINCT", query_str)-- members = self._realtime_cohort_members(cohort)- self.assertIn(str(x_and_a), members) # one from each OR branch- self.assertNotIn(str(x_and_y), members) # both from first branch only- self.assertNotIn(str(a_and_b), members) # both from second branch only- self.assertNotIn(str(neither), members) # no match- finally:- sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")-- @parameterized.expand(- [- # A merged child's internal boolean type must match the top-level operator to flatten.- # (child_is_or, top_operator, should_flatten)- ("or_child_under_or", True, PropertyOperatorType.OR, True),- ("and_child_under_and", False, PropertyOperatorType.AND, True),- ("or_child_under_and", True, PropertyOperatorType.AND, False),- ("and_child_under_or", False, PropertyOperatorType.OR, False),- ]- )- def test_collect_person_property_hashes_operator_mismatch_guard(- self, _name: str, child_is_or: bool, top_operator: PropertyOperatorType, should_flatten: bool- ) -> None:- """A merged child encodes its own AND/OR across multiple hashes. The collector must only- flatten it when the child's boolean type matches the top-level operator; a mismatch falls- through (returns None) so the parent path expresses the nested boolean correctly.-- Cohort preprocessing currently sets `_is_or_group=True` on same-key merges, so the- `and_child_under_or` direction isn't reachable end-to-end — this exercises the guard- directly to keep both directions covered.- """- cohort = Cohort.objects.create(- team=self.team,- name="guard",- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "email",- "type": "person",- "value": "x",- "negation": False,- "operator": "exact",- "conditionHash": "h0",- }- ],- }- ],- }- },- )- query = HogQLRealtimeCohortQuery(cohort=cohort)-- def merged_prop(key: str, hashes: list[str]) -> Property:- prop = Property(key=key, type="person", value="x", operator="exact", conditionHash=hashes[0])- prop._merged_condition_hashes = hashes # type: ignore[attr-defined]- prop._is_or_group = child_is_or # type: ignore[attr-defined]- return prop-- group = PropertyGroup(- type=top_operator,- values=[merged_prop("email", ["h1", "h2"]), merged_prop("plan", ["h3", "h4"])],- )- result = query._collect_person_property_hashes(group)-- if should_flatten:- self.assertIsNotNone(result)- assert result is not None- self.assertEqual(set(result[0]), {"h1", "h2", "h3", "h4"})- else:- self.assertIsNone(result)diff --git a/posthog/kafka_client/routing.py b/posthog/kafka_client/routing.pyindex 769ee94b2085..3334f7c9102d 100644--- a/posthog/kafka_client/routing.py+++ b/posthog/kafka_client/routing.py@@ -27,8 +27,6 @@ from posthog.kafka_client.client import _AsyncKafkaProducer, _KafkaProducerfrom posthog.kafka_client.profiles import KafkaClusterProfilefrom posthog.kafka_client.topics import (KAFKA_APP_METRICS2,- KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,- KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,KAFKA_CDP_INTERNAL_EVENTS,KAFKA_CLICKHOUSE_SESSION_RECORDING_EVENTS,KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS,@@ -98,8 +96,6 @@ _DEFAULT_TOPIC_ROUTING: dict[str, KafkaClusterProfile] = {KAFKA_CDP_INTERNAL_EVENTS: KafkaClusterProfile.CYCLOTRON,KAFKA_DWH_CDP_RAW_TABLE: KafkaClusterProfile.CYCLOTRON,# --- CALCULATED_EVENTS (Warpstream calculated-events) ---- KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES: KafkaClusterProfile.CALCULATED_EVENTS,- KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS: KafkaClusterProfile.CALCULATED_EVENTS,KAFKA_COHORT_MEMBERSHIP_CHANGED: KafkaClusterProfile.CALCULATED_EVENTS,# --- REPLAY (Session replay) ---KAFKA_CLICKHOUSE_SESSION_RECORDING_EVENTS: KafkaClusterProfile.REPLAY,diff --git a/posthog/kafka_client/test/test_routing.py b/posthog/kafka_client/test/test_routing.pyindex 0ce347b8bf23..170facf58134 100644--- a/posthog/kafka_client/test/test_routing.py+++ b/posthog/kafka_client/test/test_routing.py@@ -22,7 +22,6 @@ from posthog.kafka_client.routing import ()from posthog.kafka_client.topics import (KAFKA_APP_METRICS2,- KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,KAFKA_DEAD_LETTER_QUEUE,KAFKA_DWH_CDP_RAW_TABLE,KAFKA_EVENTS_JSON,@@ -116,12 +115,12 @@ class CurrentTopicRoutingTest(TestCase):self.assertEqual(mapping.get(KAFKA_APP_METRICS2), KafkaClusterProfile.INGESTION)def test_env_overrides_add_new_topic(self):- with override_settings(- KAFKA_TOPIC_ROUTING_OVERRIDES=f"{KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES}=cyclotron"- ):+ # KAFKA_DEAD_LETTER_QUEUE is deliberately absent from the defaults, so this covers+ # adding a brand-new routing key rather than overriding an existing one.+ with override_settings(KAFKA_TOPIC_ROUTING_OVERRIDES=f"{KAFKA_DEAD_LETTER_QUEUE}=cyclotron"):mapping = current_topic_routing()self.assertEqual(- mapping.get(KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES),+ mapping.get(KAFKA_DEAD_LETTER_QUEUE),KafkaClusterProfile.CYCLOTRON,)# Defaults still present.diff --git a/posthog/kafka_client/topics.py b/posthog/kafka_client/topics.pyindex ba1eceb41a06..751d5daa9045 100644--- a/posthog/kafka_client/topics.py+++ b/posthog/kafka_client/topics.py@@ -61,10 +61,6 @@ KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPIC = f"{KAFKA_PREFIX}document_embeddings_inpuKAFKA_DOCUMENT_EMBEDDING_RESULTS_TOPIC = f"{KAFKA_PREFIX}document_embedding_results{SUFFIX}"KAFKA_CDP_INTERNAL_EVENTS = f"{KAFKA_PREFIX}cdp_internal_events{SUFFIX}"-KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES = (- f"{KAFKA_PREFIX}clickhouse_precalculated_person_properties{SUFFIX}"-)-KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS = f"{KAFKA_PREFIX}clickhouse_prefiltered_events{SUFFIX}"KAFKA_CDP_BACKFILL_EVENTS = f"{KAFKA_PREFIX}cdp_backfill_events{SUFFIX}"KAFKA_COHORT_MEMBERSHIP_CHANGED = f"{KAFKA_PREFIX}cohort_membership_changed{SUFFIX}"diff --git a/posthog/management/commands/analyze_realtime_cohort_calculation.py b/posthog/management/commands/analyze_realtime_cohort_calculation.pydeleted file mode 100644index 77248cf4c35a..000000000000--- a/posthog/management/commands/analyze_realtime_cohort_calculation.py+++ /dev/null@@ -1,156 +0,0 @@-import time-import asyncio-import logging--from django.conf import settings-from django.core.management.base import BaseCommand, CommandError--import structlog-from temporalio.common import WorkflowIDReusePolicy--from posthog.temporal.common.client import async_connect-from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- RealtimeCohortCalculationCoordinatorWorkflowInputs,-)--logger = structlog.get_logger(__name__)-logger.setLevel(logging.INFO)---class Command(BaseCommand):- help = "Run realtime cohort calculation coordinator to process actions in parallel"-- def add_arguments(self, parser):- parser.add_argument(- "--parallelism",- type=int,- default=10,- help="Number of parallel child workflows to spawn (default: 10)",- )- parser.add_argument(- "--workflows-per-batch",- type=int,- default=5,- help="Number of workflows to start per batch for jittered scheduling (default: 5)",- )- parser.add_argument(- "--batch-delay-minutes",- type=int,- default=5,- help="Delay between batches in minutes (default: 5)",- )- parser.add_argument(- "--team-ids",- type=str,- default=None,- help="Comma-separated list of team IDs that should process all cohorts (optional)",- )- parser.add_argument(- "--global-percentage",- type=float,- default=None,- help="Global percentage for teams not in team-ids list (0.0 to 1.0, optional)",- )- parser.add_argument(- "--cohort-id",- type=int,- default=None,- help="Filter to a specific cohort_id (optional)",- )-- def handle(self, *args, **options):- parallelism = options.get("parallelism", 10)- workflows_per_batch = options.get("workflows_per_batch", 5)- batch_delay_minutes = options.get("batch_delay_minutes", 5)- team_ids_str = options.get("team_ids")- team_ids = None- if team_ids_str:- try:- team_ids = {int(tid.strip()) for tid in team_ids_str.split(",") if tid.strip()}- except ValueError as e:- raise CommandError(- f"Invalid team IDs format: {team_ids_str}. Expected comma-separated integers."- ) from e- global_percentage = options.get("global_percentage")- if global_percentage is not None and (global_percentage < 0.0 or global_percentage > 1.0):- raise CommandError(f"Invalid global percentage: {global_percentage}. Must be between 0.0 and 1.0.")- cohort_id = options.get("cohort_id")-- logger.info(- "Starting realtime cohort calculation coordinator",- parallelism=parallelism,- workflows_per_batch=workflows_per_batch,- batch_delay_minutes=batch_delay_minutes,- team_ids=team_ids,- global_percentage=global_percentage,- cohort_id=cohort_id,- )-- self.run_temporal_workflow(- parallelism=parallelism,- workflows_per_batch=workflows_per_batch,- batch_delay_minutes=batch_delay_minutes,- team_ids=team_ids,- global_percentage=global_percentage,- cohort_id=cohort_id,- )-- logger.info(- "Coordinator workflow scheduled child workflows",- parallelism=parallelism,- )-- self.stdout.write(f"Coordinator workflow scheduled {parallelism} child workflows")- self.stdout.write("Child workflows are running in the background. Check Temporal UI for progress and results.")-- def run_temporal_workflow(- self,- parallelism: int,- workflows_per_batch: int,- batch_delay_minutes: int,- team_ids: set[int] | None,- global_percentage: float | None,- cohort_id: int | None,- ) -> None:- """Run the Temporal workflow for parallel processing."""-- async def _run_workflow():- # Connect to Temporal- client = await async_connect()-- # Create coordinator workflow inputs- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- parallelism=parallelism,- workflows_per_batch=workflows_per_batch,- batch_delay_minutes=batch_delay_minutes,- team_ids=team_ids,- global_percentage=global_percentage,- cohort_id=cohort_id,- )-- # Generate unique workflow ID- workflow_id = f"realtime-cohort-calculation-coordinator-{int(time.time())}"-- logger.info(f"Starting Temporal coordinator workflow: {workflow_id}")-- try:- # Start the coordinator workflow (fire-and-forget)- await client.start_workflow(- "realtime-cohort-calculation-coordinator",- inputs,- id=workflow_id,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,- task_queue=settings.MESSAGING_TASK_QUEUE,- )-- logger.info(f"Workflow {workflow_id} started successfully")-- except Exception as e:- logger.exception(f"Workflow execution failed: {e}")- raise-- try:- # Run the async function- asyncio.run(_run_workflow())- except Exception as e:- logger.exception(f"Failed to execute Temporal workflow: {e}")diff --git a/posthog/management/commands/backfill_precalculated_events.py b/posthog/management/commands/backfill_precalculated_events.pydeleted file mode 100644index 190f87448ed7..000000000000--- a/posthog/management/commands/backfill_precalculated_events.py+++ /dev/null@@ -1,436 +0,0 @@-import time-import uuid-import asyncio-import datetime as dt-import dataclasses-from typing import Any--from django.conf import settings-from django.core.management.base import BaseCommand, CommandError--import structlog-from temporalio.common import WorkflowIDReusePolicy--from posthog.models.property.property import BehavioralPropertyType-from posthog.temporal.common.client import async_connect-from posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow import (- BackfillPrecalculatedEventsCoordinatorInputs,-)-from posthog.temporal.messaging.filter_storage import store_event_filters-from posthog.temporal.messaging.types import BehavioralEventFilter--from products.cohorts.backend.models.cohort import Cohort, CohortType--logger = structlog.get_logger(__name__)---class _DeduplicatedCondition:- """Accumulator for deduplicating behavioral filters across cohorts."""-- bytecode: list[Any]- event_name: str- time_value: int- time_interval: str- event_filters: list[dict] | None- cohort_ids: set[int]---# Behavioral filter types that can be compiled to bytecode for realtime evaluation-SUPPORTED_BEHAVIORAL_TYPES = {- BehavioralPropertyType.PERFORMED_EVENT,- BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE,-}--# Hard cap on backfill window to prevent runaway scans. Raise after benchmarking.-MAX_BACKFILL_DAYS = 90--# Supported time_interval values and their conversion to days-TIME_INTERVAL_TO_DAYS = {- "day": 1,- "week": 7,- "month": 30,- "year": 365,-}---def extract_behavioral_filters(cohort: Cohort) -> list[BehavioralEventFilter]:- """Extract behavioral event filters from a realtime cohort.-- Recursively traverses the filter tree to find behavioral filters with- conditionHash and bytecode that can be used for event backfilling.- Only extracts performed_event and performed_event_multiple types.- """- filters: list[BehavioralEventFilter] = []-- if not cohort.filters:- return filters-- properties = cohort.filters.get("properties")- if not properties:- return filters-- def traverse_filter_tree(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_filter_tree(child)- return-- if node_type != "behavioral":- return-- # Only extract supported behavioral types- value = node.get("value")- if value not in SUPPORTED_BEHAVIORAL_TYPES:- return-- condition_hash = node.get("conditionHash")- bytecode = node.get("bytecode")- event_name = node.get("key")-- if not condition_hash or not bytecode or not event_name:- return-- # Bytecode must be a list with header + version + at least one op- if not isinstance(bytecode, list) or len(bytecode) <= 2:- logger.warning(- "Skipping behavioral filter with invalid bytecode",- condition_hash=condition_hash,- bytecode_type=type(bytecode).__name__,- )- return-- # event_name must be a string (action IDs are ints and not supported for backfill)- if not isinstance(event_name, str):- return-- time_value = node.get("time_value")- time_interval = node.get("time_interval")-- # Parse time_value: the filter data stores it as a string- if time_value is not None:- try:- time_value = int(time_value)- except (ValueError, TypeError):- logger.warning(- "Skipping behavioral filter with invalid time_value",- condition_hash=condition_hash,- time_value=node.get("time_value"),- )- return-- # Default to 30 days if time window is missing- if time_value is None or time_interval is None:- time_value = 30- time_interval = "day"-- filters.append(- BehavioralEventFilter(- condition_hash=condition_hash,- bytecode=bytecode,- cohort_ids=[], # Populated during deduplication- event_name=event_name,- time_value=time_value,- time_interval=time_interval,- event_filters=node.get("event_filters"),- )- )-- traverse_filter_tree(properties)- return filters---def compute_backfill_days(filters: list[BehavioralEventFilter]) -> tuple[int, int]:- """Compute the number of days to backfill from filter time windows.-- Takes the maximum time window across all filters and clamps to MAX_BACKFILL_DAYS.-- Returns:- Tuple of (clamped_days, unclamped_days).- """- if not filters:- return 0, 0-- max_days = 0- for f in filters:- multiplier = TIME_INTERVAL_TO_DAYS.get(f.time_interval, 1)- filter_days = f.time_value * multiplier- max_days = max(max_days, filter_days)-- return min(max_days, MAX_BACKFILL_DAYS), max_days---class Command(BaseCommand):- help = "Backfill precalculated_events table for realtime cohorts with behavioral event filters"-- def add_arguments(self, parser):- parser.add_argument(- "--team-id",- type=int,- required=False,- help="Team ID to backfill events for. Cannot be used with --team-ids",- )- parser.add_argument(- "--team-ids",- type=int,- nargs="+",- required=False,- help="List of team IDs to backfill events for. Cannot be used with --team-id",- )- parser.add_argument(- "--cohort-id",- type=int,- required=False,- help="Optional: Specific cohort ID to backfill. Can only be used with --team-id",- )- parser.add_argument(- "--days",- type=int,- required=False,- help=f"Override the backfill time window in days (default: auto-computed from filters, max: {MAX_BACKFILL_DAYS})",- )- parser.add_argument(- "--concurrent-workflows",- type=int,- default=5,- help="Number of concurrent child workflows to run (default: 5)",- )- parser.add_argument(- "--ignore-backfilled-dates",- action="store_true",- default=False,- help="Skip the already-backfilled check and reprocess all days unconditionally",- )-- def handle(self, *args, **options):- team_id = options.get("team_id")- team_ids_option = options.get("team_ids")- cohort_id = options.get("cohort_id")- days_override = options.get("days")- concurrent_workflows = options["concurrent_workflows"]- ignore_backfilled_dates = options["ignore_backfilled_dates"]-- if team_id and team_ids_option:- raise CommandError("Cannot use both --team-id and --team-ids. Please use only one.")-- if not team_id and not team_ids_option:- raise CommandError("Must provide either --team-id or --team-ids")-- if cohort_id and team_ids_option:- raise CommandError("Cannot use --cohort-id with --team-ids. Use --cohort-id only with --team-id.")-- if days_override is not None and days_override <= 0:- raise CommandError("--days must be a positive integer")-- if team_id:- team_ids = [team_id]- else:- team_ids = sorted(set(team_ids_option or []))-- self.stdout.write(self.style.SUCCESS(f"Processing {len(team_ids)} team(s): {team_ids}"))-- for current_team_id in team_ids:- self.stdout.write(self.style.SUCCESS(f"\n=== Processing Team {current_team_id} ==="))-- if cohort_id:- try:- cohorts = [Cohort.objects.get(id=cohort_id, team_id=current_team_id)]- except Cohort.DoesNotExist:- raise CommandError(f"Cohort {cohort_id} not found for team {current_team_id}")- else:- cohorts = list(- Cohort.objects.filter(- team_id=current_team_id,- cohort_type=CohortType.REALTIME,- deleted=False,- ).order_by("id")- )- if not cohorts:- self.stdout.write(self.style.WARNING(f"No realtime cohorts found for team {current_team_id}"))- continue-- self.stdout.write(- self.style.SUCCESS(f"Found {len(cohorts)} cohort(s) to evaluate for team {current_team_id}")- )-- # Collect and deduplicate filters across all cohorts- condition_map: dict[str, _DeduplicatedCondition] = {}- cohort_ids: list[int] = []- total_original_filters = 0-- for cohort in cohorts:- if cohort.cohort_type != CohortType.REALTIME:- self.stdout.write(- self.style.WARNING(- f"Skipping cohort {cohort.id}: not a realtime cohort (type: {cohort.cohort_type})"- )- )- continue-- filters = extract_behavioral_filters(cohort)- if not filters:- self.stdout.write(- self.style.WARNING(- f"Skipping cohort {cohort.id}: no behavioral filters with conditionHash and bytecode"- )- )- continue-- cohort_ids.append(cohort.id)- total_original_filters += len(filters)- self.stdout.write(self.style.SUCCESS(f"Cohort {cohort.id}: found {len(filters)} behavioral filters"))-- for f in filters:- if f.condition_hash not in condition_map:- condition_map[f.condition_hash] = _DeduplicatedCondition(- bytecode=f.bytecode,- event_name=f.event_name,- time_value=f.time_value,- time_interval=f.time_interval,- event_filters=f.event_filters,- cohort_ids={cohort.id},- )- self.stdout.write(f" + New condition: {f.condition_hash} (event: {f.event_name})")- else:- condition_map[f.condition_hash].cohort_ids.add(cohort.id)- self.stdout.write(f" = Duplicate condition: {f.condition_hash}")-- if not condition_map:- self.stdout.write(- self.style.WARNING(f"No behavioral filters found across any cohorts for team {current_team_id}")- )- continue-- deduplicated_filters = [- BehavioralEventFilter(- condition_hash=condition_hash,- bytecode=cond.bytecode,- cohort_ids=sorted(cond.cohort_ids),- event_name=cond.event_name,- time_value=cond.time_value,- time_interval=cond.time_interval,- event_filters=cond.event_filters,- )- for condition_hash, cond in sorted(condition_map.items())- ]-- cohort_ids = sorted(cohort_ids)-- # Compute effective backfill days- if days_override is not None:- effective_days = min(days_override, MAX_BACKFILL_DAYS)- if days_override > MAX_BACKFILL_DAYS:- self.stdout.write(- self.style.WARNING(- f"--days {days_override} exceeds MAX_BACKFILL_DAYS ({MAX_BACKFILL_DAYS}), clamping to {MAX_BACKFILL_DAYS}"- )- )- else:- effective_days, auto_computed_unclamped = compute_backfill_days(deduplicated_filters)- if auto_computed_unclamped > MAX_BACKFILL_DAYS:- self.stdout.write(- self.style.WARNING(- f"Auto-computed backfill window ({auto_computed_unclamped} days) exceeds "- f"MAX_BACKFILL_DAYS ({MAX_BACKFILL_DAYS}), clamping to {MAX_BACKFILL_DAYS}"- )- )-- backfill_start = dt.datetime.now(dt.UTC) - dt.timedelta(days=effective_days)-- event_names = sorted({f.event_name for f in deduplicated_filters})-- self.stdout.write(- self.style.SUCCESS(- f"\nDeduplicated {len(deduplicated_filters)} unique conditions across {len(cohort_ids)} cohorts\n"- f" Events: {event_names}\n"- f" Backfill window: {effective_days} days (from {backfill_start.strftime('%Y-%m-%d')} to now)"- )- )- for filter_obj in deduplicated_filters:- self.stdout.write(- f" - {filter_obj.condition_hash} (event: {filter_obj.event_name}, "- f"window: {filter_obj.time_value} {filter_obj.time_interval}s, "- f"cohorts: {filter_obj.cohort_ids})"- )-- self.stdout.write(- self.style.SUCCESS(- f"\nProcessing {len(cohort_ids)} cohorts: reduced {total_original_filters} "- f"filters to {len(deduplicated_filters)} unique conditions"- )- )-- try:- workflow_id = self.run_temporal_workflow(- team_id=current_team_id,- filters=deduplicated_filters,- cohort_ids=cohort_ids,- effective_days=effective_days,- concurrent_workflows=concurrent_workflows,- ignore_backfilled_dates=ignore_backfilled_dates,- )- except Exception as e:- self.stdout.write(self.style.ERROR(f"Failed to start workflow for team {current_team_id}: {e}"))- continue-- self.stdout.write(- self.style.SUCCESS(- f"\nSuccessfully started coordinator workflow for team {current_team_id}\n"- f" Workflow ID: {workflow_id}\n"- f" Cohorts: {cohort_ids}\n"- f" Unique conditions: {len(deduplicated_filters)}\n"- f" Backfill window: {effective_days} days\n"- f" Concurrent workflows: {concurrent_workflows}"- )- )-- def run_temporal_workflow(- self,- team_id: int,- filters: list[BehavioralEventFilter],- cohort_ids: list[int],- effective_days: int,- concurrent_workflows: int,- ignore_backfilled_dates: bool = False,- ) -> str:- """Run the Temporal coordinator workflow for the team."""- filter_storage_key = store_event_filters(filters, team_id)- self.stdout.write(- self.style.SUCCESS(f"Stored {len(filters)} event filters in Redis with key: {filter_storage_key}")- )-- condition_hashes = sorted({f.condition_hash for f in filters})- workflow_id = f"backfill-precalculated-events-team-{team_id}-{int(time.time())}-{uuid.uuid4().hex[:8]}"-- async def _run_workflow():- client = await async_connect()-- inputs = BackfillPrecalculatedEventsCoordinatorInputs(- team_id=team_id,- filter_storage_key=filter_storage_key,- cohort_ids=cohort_ids,- condition_hashes=condition_hashes,- days_to_backfill=effective_days,- concurrent_workflows=concurrent_workflows,- ignore_backfilled_dates=ignore_backfilled_dates,- )-- await client.start_workflow(- "backfill-precalculated-events-coordinator",- inputs,- id=workflow_id,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,- task_queue=settings.MESSAGING_TASK_QUEUE,- )-- return workflow_id-- try:- return asyncio.run(_run_workflow())- except Exception:- logger.exception("Failed to execute Temporal workflow")- raisediff --git a/posthog/management/commands/backfill_precalculated_person_properties.py b/posthog/management/commands/backfill_precalculated_person_properties.pydeleted file mode 100644index 836eba1789ca..000000000000--- a/posthog/management/commands/backfill_precalculated_person_properties.py+++ /dev/null@@ -1,300 +0,0 @@-import time-import asyncio-from typing import Any--from django.conf import settings-from django.core.management.base import BaseCommand, CommandError--import structlog-from temporalio.common import WorkflowIDReusePolicy--from posthog.temporal.common.client import async_connect-from posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow import (- BackfillPrecalculatedPersonPropertiesCoordinatorInputs,-)-from posthog.temporal.messaging.filter_storage import extract_person_property_filters, store_filters-from posthog.temporal.messaging.types import PersonPropertyFilter--from products.cohorts.backend.models.cohort import Cohort, CohortType--logger = structlog.get_logger(__name__)---class Command(BaseCommand):- help = "Backfill precalculated_person_properties table for realtime cohorts with person property filters"-- def add_arguments(self, parser):- parser.add_argument(- "--team-id",- type=int,- required=False,- help="Team ID to backfill person properties for. Cannot be used with --team-ids",- )- parser.add_argument(- "--team-ids",- type=int,- nargs="+",- required=False,- help="List of team IDs to backfill person properties for. Cannot be used with --team-id",- )- parser.add_argument(- "--cohort-id",- type=int,- required=False,- help="Optional: Specific cohort ID to backfill. Can only be used with --team-id, not with --team-ids",- )- parser.add_argument(- "--batch-size",- type=int,- default=1000,- help="Number of persons to process per batch (default: 1000)",- )- parser.add_argument(- "--concurrent-workflows",- type=int,- default=5,- help="Number of concurrent child workflows to run (default: 5)",- )- parser.add_argument(- "--person-id",- type=str,- required=False,- help="Optional: Specific person ID (UUID) to filter the backfill for. If provided, only processes properties for this person",- )-- def handle(self, *args, **options):- team_id = options.get("team_id")- team_ids_option = options.get("team_ids")- cohort_id = options.get("cohort_id")- batch_size = options["batch_size"]- concurrent_workflows = options["concurrent_workflows"]- person_id = options.get("person_id")-- # Validate that only one team option is provided- if team_id and team_ids_option:- self.stdout.write(self.style.ERROR("Cannot use both --team-id and --team-ids. Please use only one."))- return-- # Validate that at least one team option is provided- if not team_id and not team_ids_option:- self.stdout.write(self.style.ERROR("Must provide either --team-id or --team-ids"))- return-- # Validate that cohort-id is only used with single team- if cohort_id and team_ids_option:- self.stdout.write(- self.style.ERROR("Cannot use --cohort-id with --team-ids. Use --cohort-id only with --team-id.")- )- return-- # Validate that person-id is only used with single team- if person_id and team_ids_option:- self.stdout.write(- self.style.ERROR("Cannot use --person-id with --team-ids. Use --person-id only with --team-id.")- )- return-- # Get team IDs to process- if team_id:- team_ids = [team_id]- else:- # Deduplicate and sort team_ids for deterministic processing- team_ids = sorted(set(team_ids_option or []))-- self.stdout.write(self.style.SUCCESS(f"Processing {len(team_ids)} team(s): {team_ids}"))-- # Process each team separately (each team needs its own workflow)- for current_team_id in team_ids:- self.stdout.write(self.style.SUCCESS(f"\n=== Processing Team {current_team_id} ==="))-- # Get cohorts to process for this team- if cohort_id:- # Single cohort mode- try:- cohorts = [Cohort.objects.get(id=cohort_id, team_id=current_team_id)]- except Cohort.DoesNotExist:- raise CommandError(f"Cohort {cohort_id} not found for team {current_team_id}")- else:- # All realtime cohorts for team- cohorts = list(- Cohort.objects.filter(- team_id=current_team_id,- cohort_type=CohortType.REALTIME,- deleted=False,- ).order_by("id")- )- if not cohorts:- self.stdout.write(self.style.WARNING(f"No realtime cohorts found for team {current_team_id}"))- continue-- if cohort_id:- self.stdout.write(- self.style.SUCCESS(f"Found {len(cohorts)} cohort(s) to evaluate for team {current_team_id}")- )- else:- self.stdout.write(- self.style.SUCCESS(f"Found {len(cohorts)} realtime cohort(s) to process for team {current_team_id}")- )-- # Collect and deduplicate filters across all cohorts for this team- condition_map: dict[str, tuple[list[Any], str | None, set[int]]] = {}- cohort_ids = []- total_original_filters = 0- for cohort in cohorts:- if cohort.cohort_type != CohortType.REALTIME:- self.stdout.write(- self.style.WARNING(- f"Skipping cohort {cohort.id}: not a realtime cohort (type: {cohort.cohort_type})"- )- )- continue-- # Extract person property filters- filters = extract_person_property_filters(cohort)- if not filters:- self.stdout.write(- self.style.WARNING(- f"Skipping cohort {cohort.id}: no person property filters with conditionHash and bytecode"- )- )- continue-- cohort_ids.append(cohort.id)- total_original_filters += len(filters)- self.stdout.write(- self.style.SUCCESS(f"Cohort {cohort.id}: found {len(filters)} person property filters")- )-- # Deduplicate by condition_hash- for f in filters:- if f.condition_hash not in condition_map:- condition_map[f.condition_hash] = (f.bytecode, f.property_key, {cohort.id})- self.stdout.write(f" + New condition: {f.condition_hash}")- else:- # Condition already exists, just add this cohort ID- condition_map[f.condition_hash][2].add(cohort.id)- self.stdout.write(f" = Duplicate condition: {f.condition_hash}")-- if not condition_map:- self.stdout.write(- self.style.WARNING(- f"No person property filters found across any cohorts for team {current_team_id}"- )- )- continue-- # Convert to list of PersonPropertyFilter objects with deterministic ordering- deduplicated_filters = [- PersonPropertyFilter(- condition_hash=condition_hash,- bytecode=bytecode,- property_key=property_key,- cohort_ids=sorted(cohort_set), # Sort cohort IDs for deterministic order- )- for condition_hash, (bytecode, property_key, cohort_set) in sorted(- condition_map.items()- ) # Sort by condition_hash for deterministic order- ]-- # Sort cohort_ids for deterministic workflow ordering- cohort_ids = sorted(cohort_ids)-- self.stdout.write(- self.style.SUCCESS(- f"\nDeduplicated {len(deduplicated_filters)} unique conditions across {len(cohort_ids)} cohorts"- )- )- for filter_obj in deduplicated_filters:- self.stdout.write(f" - {filter_obj.condition_hash} (used by cohorts: {filter_obj.cohort_ids})")-- # Run coordinator workflow with cursor-based sequential processing- self.stdout.write(- self.style.SUCCESS(- f"\nProcessing {len(cohort_ids)} cohorts: reduced {total_original_filters} filters to {len(deduplicated_filters)} unique conditions"- )- )-- try:- workflow_id = self.run_temporal_workflow(- team_id=current_team_id,- filters=deduplicated_filters,- cohort_ids=cohort_ids,- batch_size=batch_size,- concurrent_workflows=concurrent_workflows,- person_id=person_id,- )- except Exception as e:- self.stdout.write(self.style.ERROR(f"Failed to start workflow for team {current_team_id}: {e}"))- continue-- self.stdout.write(- self.style.SUCCESS(- f"\nSuccessfully started coordinator workflow for team {current_team_id}\n"- f" Workflow ID: {workflow_id}\n"- f" Cohorts: {cohort_ids}\n"- f" Unique conditions: {len(deduplicated_filters)}\n"- f" Batch size: {batch_size} persons per batch\n"- f" Concurrent workflows: {concurrent_workflows}"- )- )- self.stdout.write(- f"\nWorkflow is running with {concurrent_workflows} concurrent child workflows using ID-range based batching. Check Temporal UI for progress and results."- )-- def run_temporal_workflow(- self,- team_id: int,- filters: list[PersonPropertyFilter],- cohort_ids: list[int],- batch_size: int,- concurrent_workflows: int,- person_id: str | None = None,- ) -> str:- """Run the Temporal coordinator workflow for the team."""-- async def _run_workflow():- # Connect to Temporal- client = await async_connect()-- # Store filters in Redis and get storage key- filter_storage_key = store_filters(filters, team_id)- self.stdout.write(- self.style.SUCCESS(f"Stored {len(filters)} filters in Redis with key: {filter_storage_key}")- )-- # Create coordinator workflow inputs with filter storage key- inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(- team_id=team_id,- filter_storage_key=filter_storage_key,- cohort_ids=cohort_ids,- batch_size=batch_size,- concurrent_workflows=concurrent_workflows,- person_id=person_id,- single_cohort_mode=len(cohort_ids) == 1, # True when exactly one cohort is being processed- )-- # Generate unique workflow ID (one per team, based on timestamp)- workflow_id = f"backfill-precalculated-person-properties-team-{team_id}-{int(time.time())}"-- try:- # Start the coordinator workflow (fire-and-forget)- await client.start_workflow(- "backfill-precalculated-person-properties-coordinator",- inputs,- id=workflow_id,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,- task_queue=settings.MESSAGING_TASK_QUEUE,- )-- return workflow_id-- except Exception as e:- logger.exception(f"Workflow execution failed: {e}")- raise-- try:- # Run the async function- return asyncio.run(_run_workflow())- except Exception as e:- logger.exception(f"Failed to execute Temporal workflow: {e}")- raisediff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex dfb40bdb3aee..48305c82953d 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -88,10 +88,6 @@ from posthog.temporal.mcp_analytics.intent_clustering import (MCP_ANALYTICS_INTENT_CLUSTERING_ACTIVITIES,MCP_ANALYTICS_INTENT_CLUSTERING_WORKFLOWS,)-from posthog.temporal.messaging import (- ACTIVITIES as MESSAGING_ACTIVITIES,- WORKFLOWS as MESSAGING_WORKFLOWS,-)from posthog.temporal.product_analytics import (ACTIVITIES as PRODUCT_ANALYTICS_ACTIVITIES,WORKFLOWS as PRODUCT_ANALYTICS_WORKFLOWS,@@ -450,15 +446,13 @@ _task_queue_specs = [REPLAY_VISION_WORKFLOWS,REPLAY_VISION_ACTIVITIES,),- (- settings.MESSAGING_TASK_QUEUE,- MESSAGING_WORKFLOWS + WA_DIGEST_WORKFLOWS,- MESSAGING_ACTIVITIES + WA_DIGEST_ACTIVITIES,- ),+ # The web-analytics digests share this queue with the PostHog-wide weekly digest: both are+ # weekly crons with the same shape, and the messaging queue they used to sit on has no other+ # workflows left, so a dedicated fleet for them isn't worth its reserved capacity.(settings.WEEKLY_DIGEST_TASK_QUEUE,- WEEKLY_DIGEST_WORKFLOWS,- WEEKLY_DIGEST_ACTIVITIES,+ WEEKLY_DIGEST_WORKFLOWS + WA_DIGEST_WORKFLOWS,+ WEEKLY_DIGEST_ACTIVITIES + WA_DIGEST_ACTIVITIES,),(settings.LLMA_EVALS_TASK_QUEUE,diff --git a/posthog/management/commands/test/test_backfill_precalculated_events.py b/posthog/management/commands/test/test_backfill_precalculated_events.pydeleted file mode 100644index 04bff734219e..000000000000--- a/posthog/management/commands/test/test_backfill_precalculated_events.py+++ /dev/null@@ -1,911 +0,0 @@-from io import StringIO--import pytest-from posthog.test.base import BaseTest-from unittest.mock import AsyncMock, MagicMock, patch--from django.conf import settings-from django.core.management import call_command-from django.core.management.base import CommandError, OutputWrapper--from parameterized import parameterized-from temporalio.common import WorkflowIDReusePolicy--from posthog.management.commands.backfill_precalculated_events import (- MAX_BACKFILL_DAYS,- Command,- compute_backfill_days,- extract_behavioral_filters,-)-from posthog.models import Team-from posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow import (- BackfillPrecalculatedEventsCoordinatorInputs,-)-from posthog.temporal.messaging.types import BehavioralEventFilter--from products.cohorts.backend.models.cohort import Cohort, CohortType---class TestExtractBehavioralFilters(BaseTest):- def test_extracts_performed_event_filter(self):- cohort = Cohort.objects.create(- team=self.team,- name="Pageview Users",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "abc123",- "bytecode": ["_H", 1, "op1", "op2"],- }- ],- }- },- )-- filters = extract_behavioral_filters(cohort)-- assert len(filters) == 1- assert filters[0].condition_hash == "abc123"- assert filters[0].event_name == "$pageview"- assert filters[0].time_value == 30- assert filters[0].time_interval == "day"- assert filters[0].bytecode == ["_H", 1, "op1", "op2"]-- def test_extracts_performed_event_multiple_filter(self):- cohort = Cohort.objects.create(- team=self.team,- name="Frequent Users",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "purchase",- "value": "performed_event_multiple",- "event_type": "events",- "time_value": "7",- "time_interval": "week",- "operator": "gte",- "operator_value": 3,- "conditionHash": "def456",- "bytecode": ["_H", 1, "op3", "op4"],- }- ],- }- },- )-- filters = extract_behavioral_filters(cohort)-- assert len(filters) == 1- assert filters[0].condition_hash == "def456"- assert filters[0].event_name == "purchase"- assert filters[0].time_value == 7- assert filters[0].time_interval == "week"-- def test_skips_unsupported_behavioral_types(self):- cohort = Cohort.objects.create(- team=self.team,- name="First Time Users",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event_first_time",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "abc123",- "bytecode": ["_H", 1, "op1"],- },- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event_sequence",- "event_type": "events",- "conditionHash": "def456",- "bytecode": ["_H", 1, "op2"],- },- {- "type": "behavioral",- "key": "$pageview",- "value": "stopped_performing_event",- "event_type": "events",- "conditionHash": "ghi789",- "bytecode": ["_H", 1, "op3"],- },- ],- }- },- )-- filters = extract_behavioral_filters(cohort)- assert len(filters) == 0-- def test_skips_person_property_filters(self):- cohort = Cohort.objects.create(- team=self.team,- name="Mixed Filters",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "value": "[email protected]",- "operator": "exact",- "conditionHash": "person_hash",- "bytecode": ["_H", 1, "person_op"],- },- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "event_hash",- "bytecode": ["_H", 1, "event_op"],- },- ],- }- },- )-- filters = extract_behavioral_filters(cohort)-- assert len(filters) == 1- assert filters[0].condition_hash == "event_hash"-- def test_skips_filters_missing_required_fields(self):- cohort = Cohort.objects.create(- team=self.team,- name="Incomplete Filters",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- # Missing conditionHash- "bytecode": ["_H", 1, "op1"],- },- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "conditionHash": "hash1",- # Missing bytecode- },- ],- }- },- )-- filters = extract_behavioral_filters(cohort)- assert len(filters) == 0-- def test_skips_action_id_filters(self):- cohort = Cohort.objects.create(- team=self.team,- name="Action Cohort",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": 42, # Action ID (int, not str)- "value": "performed_event",- "event_type": "actions",- "time_value": "30",- "time_interval": "day",- "conditionHash": "action_hash",- "bytecode": ["_H", 1, "op1"],- }- ],- }- },- )-- filters = extract_behavioral_filters(cohort)- assert len(filters) == 0-- def test_traverses_nested_groups(self):- cohort = Cohort.objects.create(- team=self.team,- name="Nested Groups",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "hash1",- "bytecode": ["_H", 1, "op1"],- }- ],- },- {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "purchase",- "value": "performed_event",- "event_type": "events",- "time_value": "7",- "time_interval": "day",- "conditionHash": "hash2",- "bytecode": ["_H", 1, "op2"],- }- ],- },- ],- }- },- )-- filters = extract_behavioral_filters(cohort)-- assert len(filters) == 2- hashes = {f.condition_hash for f in filters}- assert hashes == {"hash1", "hash2"}-- def test_defaults_time_window_when_missing(self):- cohort = Cohort.objects.create(- team=self.team,- name="No Time Window",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- # No time_value or time_interval- "conditionHash": "hash1",- "bytecode": ["_H", 1, "op1"],- }- ],- }- },- )-- filters = extract_behavioral_filters(cohort)-- assert len(filters) == 1- assert filters[0].time_value == 30- assert filters[0].time_interval == "day"-- def test_captures_event_filters(self):- event_filters = [- {"type": "event", "key": "url", "value": "/pricing", "operator": "exact"},- ]- cohort = Cohort.objects.create(- team=self.team,- name="Filtered Events",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "hash1",- "bytecode": ["_H", 1, "op1"],- "event_filters": event_filters,- }- ],- }- },- )-- filters = extract_behavioral_filters(cohort)-- assert len(filters) == 1- assert filters[0].event_filters == event_filters-- def test_empty_cohort_filters(self):- cohort = Cohort.objects.create(- team=self.team,- name="Empty",- cohort_type=CohortType.REALTIME,- filters={},- )-- filters = extract_behavioral_filters(cohort)- assert len(filters) == 0-- def test_null_cohort_filters(self):- cohort = Cohort.objects.create(- team=self.team,- name="Null",- cohort_type=CohortType.REALTIME,- filters=None,- )-- filters = extract_behavioral_filters(cohort)- assert len(filters) == 0---class TestComputeBackfillDays(BaseTest):- @staticmethod- def _make_filter(time_value: int, time_interval: str) -> BehavioralEventFilter:- return BehavioralEventFilter(- condition_hash="test",- bytecode=["_H", 1, "op"],- cohort_ids=[1],- event_name="$pageview",- time_value=time_value,- time_interval=time_interval,- )-- @parameterized.expand(- [- ("day_30", [(30, "day")], 30, 30),- ("week_4", [(4, "week")], 28, 28),- ("month_3_clamped", [(3, "month")], MAX_BACKFILL_DAYS, 90),- ("takes_max", [(7, "day"), (30, "day"), (14, "day")], 30, 30),- ("clamps_to_max", [(365, "day")], MAX_BACKFILL_DAYS, 365),- ("unknown_interval_uses_1x", [(10, "unknown")], 10, 10),- ]- )- def test_compute_backfill_days(self, _name, filter_inputs, expected_clamped, expected_unclamped):- filters = [self._make_filter(tv, ti) for tv, ti in filter_inputs]- clamped, unclamped = compute_backfill_days(filters)- assert clamped == expected_clamped- assert unclamped == expected_unclamped-- def test_empty_filters_returns_zero(self):- assert compute_backfill_days([]) == (0, 0)---class TestBackfillPrecalculatedEventsCommand(BaseTest):- def setUp(self):- super().setUp()- self.command_output = StringIO()-- def test_cross_cohort_deduplication(self):- shared_hash = "shared_event_hash"- shared_bytecode = ["_H", 1, "op1"]-- cohort1 = Cohort.objects.create(- team=self.team,- name="Cohort A",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": shared_hash,- "bytecode": shared_bytecode,- }- ],- }- },- )-- cohort2 = Cohort.objects.create(- team=self.team,- name="Cohort B",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": shared_hash,- "bytecode": shared_bytecode,- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_events.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"- call_command("backfill_precalculated_events", "--team-id", str(self.team.id), stdout=self.command_output)-- self.assertTrue(mock_workflow.called)- call_args = mock_workflow.call_args[1]- filters = call_args["filters"]- cohort_ids = call_args["cohort_ids"]-- self.assertEqual(len(filters), 1)- self.assertEqual(set(cohort_ids), {cohort1.id, cohort2.id})- self.assertEqual(filters[0].condition_hash, shared_hash)- self.assertEqual(set(filters[0].cohort_ids), {cohort1.id, cohort2.id})-- def test_skips_cohorts_without_behavioral_filters(self):- good_cohort = Cohort.objects.create(- team=self.team,- name="Behavioral Cohort",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "hash1",- "bytecode": ["_H", 1, "op1"],- }- ],- }- },- )-- person_only_cohort = Cohort.objects.create(- team=self.team,- name="Person Property Only",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "email",- "value": "[email protected]",- "operator": "exact",- "conditionHash": "person_hash",- "bytecode": ["_H", 1, "person_op"],- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_events.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"- call_command("backfill_precalculated_events", "--team-id", str(self.team.id), stdout=self.command_output)-- call_args = mock_workflow.call_args[1]- cohort_ids = call_args["cohort_ids"]-- self.assertEqual(cohort_ids, [good_cohort.id])-- output = self.command_output.getvalue()- self.assertIn(f"Skipping cohort {person_only_cohort.id}", output)-- def test_days_override_clamped_to_max(self):- Cohort.objects.create(- team=self.team,- name="Test Cohort",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "hash1",- "bytecode": ["_H", 1, "op1"],- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_events.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"- call_command(- "backfill_precalculated_events",- "--team-id",- str(self.team.id),- "--days",- "999",- stdout=self.command_output,- )-- call_args = mock_workflow.call_args[1]- self.assertEqual(call_args["effective_days"], MAX_BACKFILL_DAYS)-- output = self.command_output.getvalue()- self.assertIn("exceeds MAX_BACKFILL_DAYS", output)-- def test_auto_computes_days_from_filters(self):- Cohort.objects.create(- team=self.team,- name="Short Window",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "7",- "time_interval": "day",- "conditionHash": "hash1",- "bytecode": ["_H", 1, "op1"],- }- ],- }- },- )-- Cohort.objects.create(- team=self.team,- name="Long Window",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "purchase",- "value": "performed_event",- "event_type": "events",- "time_value": "60",- "time_interval": "day",- "conditionHash": "hash2",- "bytecode": ["_H", 1, "op2"],- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_events.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"- call_command("backfill_precalculated_events", "--team-id", str(self.team.id), stdout=self.command_output)-- call_args = mock_workflow.call_args[1]- self.assertEqual(call_args["effective_days"], 60)-- def test_no_realtime_cohorts_shows_warning(self):- call_command("backfill_precalculated_events", "--team-id", str(self.team.id), stdout=self.command_output)-- output = self.command_output.getvalue()- self.assertIn("No realtime cohorts found", output)-- def test_validation_rejects_both_team_id_and_team_ids(self):- with pytest.raises(CommandError, match="Cannot use both"):- call_command(- "backfill_precalculated_events",- "--team-id",- "1",- "--team-ids",- "2",- "3",- stdout=self.command_output,- )-- def test_validation_rejects_negative_days(self):- with pytest.raises(CommandError, match="--days must be a positive integer"):- call_command(- "backfill_precalculated_events",- "--team-id",- str(self.team.id),- "--days",- "-1",- stdout=self.command_output,- )-- def test_team_ids_processes_multiple_teams(self):- team2 = Team.objects.create(organization=self.organization, name="Team 2")-- Cohort.objects.create(- team=self.team,- name="Cohort Team 1",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "hash_t1",- "bytecode": ["_H", 1, "op1"],- }- ],- }- },- )-- Cohort.objects.create(- team=team2,- name="Cohort Team 2",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "purchase",- "value": "performed_event",- "event_type": "events",- "time_value": "14",- "time_interval": "day",- "conditionHash": "hash_t2",- "bytecode": ["_H", 1, "op2"],- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_events.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"- call_command(- "backfill_precalculated_events",- "--team-ids",- str(self.team.id),- str(team2.id),- stdout=self.command_output,- )-- self.assertEqual(mock_workflow.call_count, 2)- team_ids_called = sorted(call[1]["team_id"] for call in mock_workflow.call_args_list)- self.assertEqual(team_ids_called, sorted([self.team.id, team2.id]))-- def test_cohort_id_restricts_to_specific_cohort(self):- target_cohort = Cohort.objects.create(- team=self.team,- name="Target Cohort",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "$pageview",- "value": "performed_event",- "event_type": "events",- "time_value": "30",- "time_interval": "day",- "conditionHash": "target_hash",- "bytecode": ["_H", 1, "op1"],- }- ],- }- },- )-- Cohort.objects.create(- team=self.team,- name="Other Cohort",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "behavioral",- "key": "purchase",- "value": "performed_event",- "event_type": "events",- "time_value": "7",- "time_interval": "day",- "conditionHash": "other_hash",- "bytecode": ["_H", 1, "op2"],- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_events.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"- call_command(- "backfill_precalculated_events",- "--team-id",- str(self.team.id),- "--cohort-id",- str(target_cohort.id),- stdout=self.command_output,- )-- self.assertTrue(mock_workflow.called)- call_args = mock_workflow.call_args[1]- filters = call_args["filters"]- cohort_ids = call_args["cohort_ids"]-- self.assertEqual(len(filters), 1)- self.assertEqual(filters[0].condition_hash, "target_hash")- self.assertEqual(cohort_ids, [target_cohort.id])---class TestRunTemporalWorkflow(BaseTest):- def setUp(self):- super().setUp()- self.command = Command()- self.command.stdout = OutputWrapper(StringIO())- self.filters = [- BehavioralEventFilter(- condition_hash="hash_1",- event_name="$pageview",- bytecode=["_H", 1, "op"],- time_value=30,- time_interval="day",- cohort_ids=[1, 2],- ),- BehavioralEventFilter(- condition_hash="hash_2",- event_name="$autocapture",- bytecode=["_H", 1, "op"],- time_value=7,- time_interval="day",- cohort_ids=[2],- ),- ]-- def test_starts_workflow_with_expected_inputs_and_task_queue(self):- mock_client = MagicMock()- mock_client.start_workflow = AsyncMock()-- with (- patch(- "posthog.management.commands.backfill_precalculated_events.async_connect",- new=AsyncMock(return_value=mock_client),- ),- patch(- "posthog.management.commands.backfill_precalculated_events.store_event_filters",- return_value="redis-key",- ) as mock_store,- ):- workflow_id = self.command.run_temporal_workflow(- team_id=self.team.id,- filters=self.filters,- cohort_ids=[1, 2],- effective_days=14,- concurrent_workflows=5,- ignore_backfilled_dates=False,- )-- mock_store.assert_called_once_with(self.filters, self.team.id)- mock_client.start_workflow.assert_awaited_once()- args, kwargs = mock_client.start_workflow.call_args- self.assertEqual(args[0], "backfill-precalculated-events-coordinator")- inputs = args[1]- self.assertIsInstance(inputs, BackfillPrecalculatedEventsCoordinatorInputs)- self.assertEqual(inputs.team_id, self.team.id)- self.assertEqual(inputs.filter_storage_key, "redis-key")- self.assertEqual(inputs.cohort_ids, [1, 2])- self.assertEqual(inputs.condition_hashes, ["hash_1", "hash_2"])- self.assertEqual(inputs.days_to_backfill, 14)- self.assertEqual(inputs.concurrent_workflows, 5)- self.assertFalse(inputs.ignore_backfilled_dates)- self.assertEqual(kwargs["task_queue"], settings.MESSAGING_TASK_QUEUE)- self.assertEqual(kwargs["id_reuse_policy"], WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY)- self.assertEqual(kwargs["id"], workflow_id)- self.assertTrue(workflow_id.startswith(f"backfill-precalculated-events-team-{self.team.id}-"))-- def test_workflow_id_is_unique_across_rapid_invocations(self):- mock_client = MagicMock()- mock_client.start_workflow = AsyncMock()-- ids: list[str] = []- with (- patch(- "posthog.management.commands.backfill_precalculated_events.async_connect",- new=AsyncMock(return_value=mock_client),- ),- patch(- "posthog.management.commands.backfill_precalculated_events.store_event_filters",- return_value="redis-key",- ),- ):- for _ in range(5):- ids.append(- self.command.run_temporal_workflow(- team_id=self.team.id,- filters=self.filters,- cohort_ids=[1, 2],- effective_days=14,- concurrent_workflows=5,- )- )-- self.assertEqual(len(set(ids)), len(ids))-- def test_raises_when_start_workflow_fails(self):- mock_client = MagicMock()- mock_client.start_workflow = AsyncMock(side_effect=RuntimeError("boom"))-- with (- patch(- "posthog.management.commands.backfill_precalculated_events.async_connect",- new=AsyncMock(return_value=mock_client),- ),- patch(- "posthog.management.commands.backfill_precalculated_events.store_event_filters",- return_value="redis-key",- ),- pytest.raises(RuntimeError, match="boom"),- ):- self.command.run_temporal_workflow(- team_id=self.team.id,- filters=self.filters,- cohort_ids=[1, 2],- effective_days=14,- concurrent_workflows=5,- )diff --git a/posthog/management/commands/test/test_backfill_precalculated_person_properties.py b/posthog/management/commands/test/test_backfill_precalculated_person_properties.pydeleted file mode 100644index ffcf10b9d035..000000000000--- a/posthog/management/commands/test/test_backfill_precalculated_person_properties.py+++ /dev/null@@ -1,411 +0,0 @@-from io import StringIO--from posthog.test.base import BaseTest-from unittest.mock import patch--from django.core.management import call_command--from products.cohorts.backend.models.cohort import Cohort, CohortType---class BackfillPrecalculatedPersonPropertiesCommandTestCase(BaseTest):- """Tests for the backfill_precalculated_person_properties management command."""-- def setUp(self):- super().setUp()- self.command_output = StringIO()-- def test_cross_cohort_deduplication_single_shared_condition(self):- """Test that filters with the same condition_hash are deduplicated across cohorts."""-- # Create cohorts with shared condition_hash- shared_condition_hash = "age_filter_25_exact"- shared_bytecode = ["mock_bytecode_age_25"]-- cohort1 = Cohort.objects.create(- team=self.team,- name="Young Users A",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "age",- "value": 25,- "operator": "exact",- "conditionHash": shared_condition_hash,- "bytecode": shared_bytecode,- }- ],- }- },- )-- cohort2 = Cohort.objects.create(- team=self.team,- name="Young Users B",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "age",- "value": 25,- "operator": "exact",- "conditionHash": shared_condition_hash,- "bytecode": shared_bytecode,- }- ],- }- },- )-- # Mock the workflow run to capture the inputs- with patch(- "posthog.management.commands.backfill_precalculated_person_properties.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"-- call_command(- "backfill_precalculated_person_properties", "--team-id", str(self.team.id), stdout=self.command_output- )-- # Verify the workflow was called- self.assertTrue(mock_workflow.called)- call_args = mock_workflow.call_args[1]- filters = call_args["filters"]- cohort_ids = call_args["cohort_ids"]-- # Should have 1 filter shared by 2 cohorts- self.assertEqual(len(filters), 1)- self.assertEqual(set(cohort_ids), {cohort1.id, cohort2.id})-- # The shared condition should be present with both cohorts- self.assertEqual(filters[0].condition_hash, shared_condition_hash)- self.assertEqual(filters[0].bytecode, shared_bytecode)- self.assertEqual(set(filters[0].cohort_ids), {cohort1.id, cohort2.id})-- # Verify output shows deduplication- output = self.command_output.getvalue()- self.assertIn("= Duplicate condition:", output)- self.assertIn(shared_condition_hash, output)-- def test_cross_cohort_deduplication_multiple_shared_conditions(self):- """Test deduplication with multiple shared conditions across three cohorts."""-- age_condition_hash = "age_filter_25"- age_bytecode = ["mock_bytecode_age_25"]- country_condition_hash = "country_filter_us"- country_bytecode = ["mock_bytecode_country_us"]-- # Cohort 1: Age + Country filters- cohort1 = Cohort.objects.create(- team=self.team,- name="Young US Users",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "age",- "value": 25,- "operator": "exact",- "conditionHash": age_condition_hash,- "bytecode": age_bytecode,- },- {- "type": "person",- "key": "country",- "value": "US",- "operator": "exact",- "conditionHash": country_condition_hash,- "bytecode": country_bytecode,- },- ],- }- },- )-- # Cohort 2: Only Age filter (shared)- cohort2 = Cohort.objects.create(- team=self.team,- name="Young Users",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "age",- "value": 25,- "operator": "exact",- "conditionHash": age_condition_hash,- "bytecode": age_bytecode,- }- ],- }- },- )-- # Cohort 3: Only Country filter (shared)- cohort3 = Cohort.objects.create(- team=self.team,- name="US Users",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "country",- "value": "US",- "operator": "exact",- "conditionHash": country_condition_hash,- "bytecode": country_bytecode,- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_person_properties.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"-- call_command(- "backfill_precalculated_person_properties", "--team-id", str(self.team.id), stdout=self.command_output- )-- call_args = mock_workflow.call_args[1]- filters = call_args["filters"]- cohort_ids = call_args["cohort_ids"]-- # Should have 2 unique filters and 3 cohorts- self.assertEqual(len(filters), 2)- self.assertEqual(set(cohort_ids), {cohort1.id, cohort2.id, cohort3.id})-- # Find the age and country filters- age_filter = next(f for f in filters if f.condition_hash == age_condition_hash)- country_filter = next(f for f in filters if f.condition_hash == country_condition_hash)-- # Verify the age condition is shared by cohorts 1 and 2- self.assertEqual(age_filter.bytecode, age_bytecode)- self.assertEqual(set(age_filter.cohort_ids), {cohort1.id, cohort2.id})-- # Verify the country condition is shared by cohorts 1 and 3- self.assertEqual(country_filter.bytecode, country_bytecode)- self.assertEqual(set(country_filter.cohort_ids), {cohort1.id, cohort3.id})-- # Verify output shows deduplication for both shared conditions- output = self.command_output.getvalue()- self.assertIn("= Duplicate condition:", output)- self.assertIn("reduced 4 filters to 2 unique conditions", output)-- def test_no_deduplication_when_all_conditions_unique(self):- """Test that no deduplication occurs when all conditions are unique."""-- Cohort.objects.create(- team=self.team,- name="Young Users",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "age",- "value": 25,- "operator": "exact",- "conditionHash": "age_filter_25",- "bytecode": ["mock_bytecode_age_25"],- }- ],- }- },- )-- Cohort.objects.create(- team=self.team,- name="Old Users",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "age",- "value": 65,- "operator": "exact",- "conditionHash": "age_filter_65",- "bytecode": ["mock_bytecode_age_65"],- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_person_properties.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"-- call_command(- "backfill_precalculated_person_properties", "--team-id", str(self.team.id), stdout=self.command_output- )-- call_args = mock_workflow.call_args[1]- filters = call_args["filters"]- cohort_ids = call_args["cohort_ids"]-- # Should have 2 unique filters (no deduplication)- self.assertEqual(len(filters), 2)- self.assertEqual(len(cohort_ids), 2)-- # Each condition should be used by exactly one cohort- for filter_obj in filters:- self.assertEqual(len(filter_obj.cohort_ids), 1)-- # Verify output shows all new conditions- output = self.command_output.getvalue()- self.assertIn("+ New condition:", output)- self.assertNotIn("= Duplicate condition:", output)- self.assertIn("reduced 2 filters to 2 unique conditions", output)-- def test_skips_cohorts_without_person_property_filters(self):- """Test that cohorts without person property filters are skipped."""-- # Create one cohort with person property filters- good_cohort = Cohort.objects.create(- team=self.team,- name="Good Cohort",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "age",- "value": 25,- "operator": "exact",- "conditionHash": "age_filter_25",- "bytecode": ["mock_bytecode_age_25"],- }- ],- }- },- )-- # Create cohort without person property filters- bad_cohort = Cohort.objects.create(- team=self.team,- name="Bad Cohort",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "event", # Not a person property filter- "key": "event_name",- "value": "signup",- "operator": "exact",- }- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_person_properties.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"-- call_command(- "backfill_precalculated_person_properties", "--team-id", str(self.team.id), stdout=self.command_output- )-- call_args = mock_workflow.call_args[1]- filters = call_args["filters"]- cohort_ids = call_args["cohort_ids"]-- # Should only have 1 cohort and 1 filter (the good one)- self.assertEqual(len(filters), 1)- self.assertEqual(cohort_ids, [good_cohort.id])-- # Verify output shows skipping- output = self.command_output.getvalue()- self.assertIn(f"Skipping cohort {bad_cohort.id}: no person property filters", output)-- def test_preserves_duplicate_condition_within_same_cohort(self):- """Test that duplicate condition_hash within same cohort doesn't create duplicate entries."""-- shared_condition_hash = "age_filter_25"- shared_bytecode = ["mock_bytecode_age_25"]-- # Create cohort with duplicate condition_hash within same cohort- Cohort.objects.create(- team=self.team,- name="Cohort with Duplicates",- cohort_type=CohortType.REALTIME,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "person",- "key": "age",- "value": 25,- "operator": "exact",- "conditionHash": shared_condition_hash,- "bytecode": shared_bytecode,- },- {- "type": "person",- "key": "age", # Same condition appears twice- "value": 25,- "operator": "exact",- "conditionHash": shared_condition_hash, # Same hash- "bytecode": shared_bytecode,- },- ],- }- },- )-- with patch(- "posthog.management.commands.backfill_precalculated_person_properties.Command.run_temporal_workflow"- ) as mock_workflow:- mock_workflow.return_value = "test-workflow-id"-- call_command(- "backfill_precalculated_person_properties", "--team-id", str(self.team.id), stdout=self.command_output- )-- call_args = mock_workflow.call_args[1]- filters = call_args["filters"]- cohort_ids = call_args["cohort_ids"]-- # Should have 1 unique filter (intra-cohort deduplication)- self.assertEqual(len(filters), 1)- self.assertEqual(len(cohort_ids), 1)-- # The condition should be present with the correct cohort- filter_obj = filters[0]- self.assertEqual(filter_obj.condition_hash, shared_condition_hash)- self.assertEqual(set(filter_obj.cohort_ids), {cohort_ids[0]})-- # Verify the set-based deduplication worked- output = self.command_output.getvalue()- self.assertIn("reduced 2 filters to 1 unique conditions", output)diff --git a/posthog/management/commands/test/test_start_temporal_worker.py b/posthog/management/commands/test/test_start_temporal_worker.pyindex 5be99499edbd..b0d9c9d77273 100644--- a/posthog/management/commands/test/test_start_temporal_worker.py+++ b/posthog/management/commands/test/test_start_temporal_worker.py@@ -1,6 +1,13 @@import pytest-from posthog.management.commands.start_temporal_worker import DATA_SYNC_WORKFLOWS, workflows_include_data_import_syncs+from posthog.management.commands.start_temporal_worker import (+ DATA_SYNC_WORKFLOWS,+ WA_DIGEST_ACTIVITIES,+ WA_DIGEST_WORKFLOWS,+ WEEKLY_DIGEST_WORKFLOWS,+ _task_queue_specs,+ workflows_include_data_import_syncs,+)class _NotADataSyncWorkflow:@@ -23,3 +30,21 @@ class _NotADataSyncWorkflow:)def test_only_data_import_queues_warm_sources(workflows: list[type], expected: bool) -> None:assert workflows_include_data_import_syncs(workflows) is expected+++# The WA digest schedules name their task queue explicitly, so if these workflows stop being+# registered alongside the queue that serves it, the schedules still fire and nothing polls them,+# which stays invisible for a week because both digests are weekly. Registration has two halves, and+# a workflow registered without its activities fails at runtime the moment it dispatches one, so both+# are asserted. Queue settings collapse to a single dev queue under DEBUG, so match on the spec entry+# that carries the weekly digest rather than on a queue name.+def test_wa_digests_are_registered_with_the_weekly_digest() -> None:+ entries = [+ (workflows, activities)+ for _, workflows, activities in _task_queue_specs+ if WEEKLY_DIGEST_WORKFLOWS[0] in workflows+ ]+ assert len(entries) == 1+ workflows, activities = entries[0]+ assert set(WA_DIGEST_WORKFLOWS) <= set(workflows)+ assert set(WA_DIGEST_ACTIVITIES) <= set(activities)diff --git a/posthog/settings/kafka.py b/posthog/settings/kafka.pyindex dded22aa3efe..cc7c70d372e8 100644--- a/posthog/settings/kafka.py+++ b/posthog/settings/kafka.py@@ -217,5 +217,5 @@ KAFKA_BASE64_KEYS: bool = get_from_env("KAFKA_BASE64_KEYS", False, type_cast=str# Per-topic overrides for the kafka_client.routing map. Comma-separated# "topic=profile" entries; merged over the code-level defaults at lookup time.-# Example: "clickhouse_precalculated_person_properties=warpstream_calculated_events"+# Example: "cohort_membership_changed=calculated_events"KAFKA_TOPIC_ROUTING_OVERRIDES: str = os.getenv("KAFKA_TOPIC_ROUTING_OVERRIDES", "") or ""diff --git a/posthog/settings/schedules.py b/posthog/settings/schedules.pyindex ddae99504f64..38c30b98c3a2 100644--- a/posthog/settings/schedules.py+++ b/posthog/settings/schedules.py@@ -56,23 +56,3 @@ CLEAR_CLICKHOUSE_DELETED_PERSON_SCHEDULE_CRON = get_from_env(# Every third month 5AM UTC on 1st of the month"0 5 1 */3 *",)--# Cohort selection for the Python realtime cohort calculation coordinator, which no longer has a-# schedule (rust/cohort-stream-processor replaced it). These survive only because the coordinator-# still parses them, and go away with the Python implementation. Unrelated to-# REALTIME_COHORT_TEAM_ALLOWLIST, which is the live setting Rust and Django both read.-# Teams that should process all their cohorts (comma-separated team IDs)-# Example: "2,42" means team 2 and team 42 process all cohorts-REALTIME_COHORT_CALCULATION_TEAMS: set[int] = {- int(team_id.strip())- for team_id in get_from_env("REALTIME_COHORT_CALCULATION_TEAMS", "2").split(",")- if team_id.strip()-}--# Global percentage for teams not in REALTIME_COHORT_CALCULATION_TEAMS (0.0 to 1.0)-# Example: 0.5 means 50% of cohorts for all other teams-REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE: float = get_from_env(- "REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE",- 0.0,- type_cast=float,-)diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex b124b3926da4..115192ed2f46 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -177,23 +177,6 @@ STAMPHOG_TASK_QUEUE = _set_temporal_task_queue("stamphog-task-queue")TEST_TASK_QUEUE = _set_temporal_task_queue("test-task-queue")BILLING_TASK_QUEUE = _set_temporal_task_queue("billing-task-queue")VIDEO_EXPORT_TASK_QUEUE = _set_temporal_task_queue("video-export-task-queue")-MESSAGING_TASK_QUEUE = _set_temporal_task_queue("messaging-task-queue")-# Per-worker cap on concurrent offline-cluster ClickHouse queries issued by the messaging-# workflow family (reconcile-precalculated-data + realtime-cohort-calculation + the precalculated-# backfills). They share one worker/event loop and the offline `default` user-# (max_concurrent_queries=30), so an unbounded fan-out across tiers can trip-# TOO_MANY_SIMULTANEOUS_QUERIES. Kept safely below 30, leaving headroom for other offline-# consumers. Note this is per worker process, so the aggregate is this value times the number of-# messaging worker replicas — size it accordingly.-#-# This is also the effective ceiling on reconcile parallelism: a reconcile activity holds one slot-# for its whole streaming context, so raising RECONCILE_PRECALCULATED_DATA_TEAM_CONCURRENCY above-# this value only queues the extra teams on the semaphore instead of running more queries at once.-# Keep this at least as large as that concurrency, or a burst of reconcile teams can occupy every-# slot and stall realtime-cohort activities (60-min start_to_close_timeout) while they wait.-MESSAGING_CLICKHOUSE_MAX_CONCURRENT_QUERIES: int = get_from_env(- "MESSAGING_CLICKHOUSE_MAX_CONCURRENT_QUERIES", 10, type_cast=int-)ANALYTICS_PLATFORM_TASK_QUEUE = _set_temporal_task_queue("analytics-platform-task-queue")SESSION_REPLAY_TASK_QUEUE = _set_temporal_task_queue("session-replay-task-queue")REPLAY_VISION_TASK_QUEUE = _set_temporal_task_queue("replay-vision-task-queue")diff --git a/posthog/templates/admin/backfill_precalculated_events.html b/posthog/templates/admin/backfill_precalculated_events.htmldeleted file mode 100644index e32207f3d1d1..000000000000--- a/posthog/templates/admin/backfill_precalculated_events.html+++ /dev/null@@ -1,115 +0,0 @@-{% extends "admin/base_site.html" %}-{% load i18n admin_urls static %}--{% block extrastyle %}-{{ block.super }}-<style>- .form-row {- margin-bottom: 15px;- }- .help {- font-size: 11px;- color: #666;- }- .submit-row {- margin-top: 30px;- }- .alert {- padding: 10px;- margin: 20px 0;- border-radius: 5px;- }- .alert-info {- background: #e3f2fd;- border: 1px solid #90caf9;- color: #1565c0;- }-</style>-{% endblock %}--{% block content %}-<div class="alert alert-info">- <strong>Note:</strong> This tool triggers the Temporal workflow to backfill the precalculated_events table- for realtime cohorts with behavioral event filters. The backfill scans historical events in daily chunks- and evaluates behavioral filter bytecodes against them. Check the Temporal UI for progress and results.-</div>--{% if messages %}- {% for message in messages %}- <div class="alert alert-{{ message.tags }}">- {{ message }}- </div>- {% endfor %}-{% endif %}--<form method="post" id="backfill-form">- {% csrf_token %}-- <fieldset class="module aligned">- <h2>Target Cohort</h2>-- <div class="form-row">- <label for="{{ form.team_id.id_for_label }}" class="required">- {{ form.team_id.label }}:- </label>- {{ form.team_id }}- {% if form.team_id.help_text %}- <p class="help">{{ form.team_id.help_text }}</p>- {% endif %}- {{ form.team_id.errors }}- </div>-- <div class="form-row">- <label for="{{ form.cohort_id.id_for_label }}">- {{ form.cohort_id.label }}:- </label>- {{ form.cohort_id }}- {% if form.cohort_id.help_text %}- <p class="help">{{ form.cohort_id.help_text }}</p>- {% endif %}- {{ form.cohort_id.errors }}- </div>- </fieldset>-- <fieldset class="module aligned">- <h2>Processing Configuration</h2>-- <div class="form-row">- <label for="{{ form.days.id_for_label }}">- {{ form.days.label }}:- </label>- {{ form.days }}- {% if form.days.help_text %}- <p class="help">{{ form.days.help_text }}</p>- {% endif %}- {{ form.days.errors }}- </div>-- <div class="form-row">- <label for="{{ form.concurrent_workflows.id_for_label }}" class="required">- {{ form.concurrent_workflows.label }}:- </label>- {{ form.concurrent_workflows }}- {% if form.concurrent_workflows.help_text %}- <p class="help">{{ form.concurrent_workflows.help_text }}</p>- {% endif %}- {{ form.concurrent_workflows.errors }}- </div>-- <div class="form-row">- <label for="{{ form.ignore_backfilled_dates.id_for_label }}">- {{ form.ignore_backfilled_dates.label }}:- </label>- {{ form.ignore_backfilled_dates }}- {% if form.ignore_backfilled_dates.help_text %}- <p class="help">{{ form.ignore_backfilled_dates.help_text }}</p>- {% endif %}- {{ form.ignore_backfilled_dates.errors }}- </div>- </fieldset>-- <div class="submit-row">- <input type="submit" value="Run Backfill" class="default" />- </div>-</form>-{% endblock %}diff --git a/posthog/templates/admin/backfill_precalculated_person_properties.html b/posthog/templates/admin/backfill_precalculated_person_properties.htmldeleted file mode 100644index a52c783f803e..000000000000--- a/posthog/templates/admin/backfill_precalculated_person_properties.html+++ /dev/null@@ -1,115 +0,0 @@-{% extends "admin/base_site.html" %}-{% load i18n admin_urls static %}--{% block extrastyle %}-{{ block.super }}-<style>- .form-row {- margin-bottom: 15px;- }- .help {- font-size: 11px;- color: #666;- }- .submit-row {- margin-top: 30px;- }- .alert {- padding: 10px;- margin: 20px 0;- border-radius: 5px;- }- .alert-info {- background: #e3f2fd;- border: 1px solid #90caf9;- color: #1565c0;- }-</style>-{% endblock %}--{% block content %}-<div class="alert alert-info">- <strong>Note:</strong> This tool triggers the Temporal workflow to backfill the precalculated_person_properties table- for realtime cohorts with person property filters. The backfill runs with configurable concurrent child workflows using ID-range based batching- and processes persons efficiently. Check the Temporal UI for progress and results.-</div>--{% if messages %}- {% for message in messages %}- <div class="alert alert-{{ message.tags }}">- {{ message }}- </div>- {% endfor %}-{% endif %}--<form method="post" id="backfill-form">- {% csrf_token %}-- <fieldset class="module aligned">- <h2>Target Cohort</h2>-- <div class="form-row">- <label for="{{ form.team_id.id_for_label }}" class="required">- {{ form.team_id.label }}:- </label>- {{ form.team_id }}- {% if form.team_id.help_text %}- <p class="help">{{ form.team_id.help_text }}</p>- {% endif %}- {{ form.team_id.errors }}- </div>-- <div class="form-row">- <label for="{{ form.cohort_id.id_for_label }}">- {{ form.cohort_id.label }}:- </label>- {{ form.cohort_id }}- {% if form.cohort_id.help_text %}- <p class="help">{{ form.cohort_id.help_text }}</p>- {% endif %}- {{ form.cohort_id.errors }}- </div>-- <div class="form-row">- <label for="{{ form.person_id.id_for_label }}">- {{ form.person_id.label }}:- </label>- {{ form.person_id }}- {% if form.person_id.help_text %}- <p class="help">{{ form.person_id.help_text }}</p>- {% endif %}- {{ form.person_id.errors }}- </div>- </fieldset>-- <fieldset class="module aligned">- <h2>Processing Configuration</h2>-- <div class="form-row">- <label for="{{ form.batch_size.id_for_label }}" class="required">- {{ form.batch_size.label }}:- </label>- {{ form.batch_size }}- {% if form.batch_size.help_text %}- <p class="help">{{ form.batch_size.help_text }}</p>- {% endif %}- {{ form.batch_size.errors }}- </div>-- <div class="form-row">- <label for="{{ form.concurrent_workflows.id_for_label }}" class="required">- {{ form.concurrent_workflows.label }}:- </label>- {{ form.concurrent_workflows }}- {% if form.concurrent_workflows.help_text %}- <p class="help">{{ form.concurrent_workflows.help_text }}</p>- {% endif %}- {{ form.concurrent_workflows.errors }}- </div>- </fieldset>-- <div class="submit-row">- <input type="submit" value="Run Backfill" class="default" />- </div>-</form>-{% endblock %}diff --git a/posthog/templates/admin/realtime_cohort_calculation.html b/posthog/templates/admin/realtime_cohort_calculation.htmldeleted file mode 100644index fd2badc4f61d..000000000000--- a/posthog/templates/admin/realtime_cohort_calculation.html+++ /dev/null@@ -1,114 +0,0 @@-{% extends "admin/base_site.html" %}-{% load i18n admin_urls static %}--{% block extrastyle %}-{{ block.super }}-<style>- .form-row {- margin-bottom: 15px;- }- .help {- font-size: 11px;- color: #666;- }- .submit-row {- margin-top: 30px;- }- .alert {- padding: 10px;- margin: 20px 0;- border-radius: 5px;- }- .alert-info {- background: #e3f2fd;- border: 1px solid #90caf9;- color: #1565c0;- }-</style>-{% endblock %}--{% block content %}-<div class="alert alert-info">- <strong>Note:</strong> This tool triggers the Temporal workflow for realtime cohort calculation.- The calculation runs asynchronously in the background and processes all actions with bytecode.- Check the Temporal UI for progress and results.-</div>--{% if messages %}- {% for message in messages %}- <div class="alert alert-{{ message.tags }}">- {{ message }}- </div>- {% endfor %}-{% endif %}--<form method="post" id="actions-analysis-form">- {% csrf_token %}-- <fieldset class="module aligned">- <h2>Configuration</h2>-- <div class="form-row">- <label for="{{ form.team_ids.id_for_label }}">{{ form.team_ids.label }}:</label>- {{ form.team_ids }}- {% if form.team_ids.help_text %}<p class="help">{{ form.team_ids.help_text }}</p>{% endif %}- {{ form.team_ids.errors }}- </div>-- <div class="form-row">- <label for="{{ form.global_percentage.id_for_label }}">{{ form.global_percentage.label }}:</label>- {{ form.global_percentage }}- {% if form.global_percentage.help_text %}<p class="help">{{ form.global_percentage.help_text }}</p>{% endif %}- {{ form.global_percentage.errors }}- </div>-- <div class="form-row">- <label for="{{ form.cohort_id.id_for_label }}">{{ form.cohort_id.label }}:</label>- {{ form.cohort_id }}- {% if form.cohort_id.help_text %}<p class="help">{{ form.cohort_id.help_text }}</p>{% endif %}- {{ form.cohort_id.errors }}- </div>-- <div class="form-row">- <label for="{{ form.parallelism.id_for_label }}" class="required">- {{ form.parallelism.label }}:- </label>- {{ form.parallelism }}- {% if form.parallelism.help_text %}- <p class="help">{{ form.parallelism.help_text }}</p>- {% endif %}- {{ form.parallelism.errors }}- </div>- </fieldset>-- <fieldset class="module aligned">- <h2>Jittered Scheduling</h2>-- <div class="form-row">- <label for="{{ form.workflows_per_batch.id_for_label }}" class="required">- {{ form.workflows_per_batch.label }}:- </label>- {{ form.workflows_per_batch }}- {% if form.workflows_per_batch.help_text %}- <p class="help">{{ form.workflows_per_batch.help_text }}</p>- {% endif %}- {{ form.workflows_per_batch.errors }}- </div>-- <div class="form-row">- <label for="{{ form.batch_delay_minutes.id_for_label }}" class="required">- {{ form.batch_delay_minutes.label }}:- </label>- {{ form.batch_delay_minutes }}- {% if form.batch_delay_minutes.help_text %}- <p class="help">{{ form.batch_delay_minutes.help_text }}</p>- {% endif %}- {{ form.batch_delay_minutes.errors }}- </div>- </fieldset>-- <div class="submit-row">- <input type="submit" value="Run Calculation" class="default" />- </div>-</form>-{% endblock %}\ No newline at end of filediff --git a/posthog/templates/custom_tools/app.html b/posthog/templates/custom_tools/app.htmlindex 032811ae9ce6..83c9e15b9fa8 100644--- a/posthog/templates/custom_tools/app.html+++ b/posthog/templates/custom_tools/app.html@@ -13,12 +13,6 @@<caption><a href="/admin/" class="section" title="Custom Tools">Custom Tools</a></caption>- <tr class="model-actionsanalysis">- <td scope="row">- <a href="{% url 'realtime-cohorts-calculation' %}">Realtime Cohorts Calculation</a>- </td>- <td>Run realtime cohorts calculation workflow</td>- </tr><tr class="model-resavecohorts"><td scope="row"><a href="{% url 'resave-cohorts' %}">Resave Cohorts (Regenerate Bytecode & Type)</a>@@ -37,18 +31,6 @@</td><td>Manage email addresses that bypass email MFA verification</td></tr>- <tr class="model-backfillprecalculatedpersonproperties">- <td scope="row">- <a href="{% url 'backfill-precalculated-person-properties' %}">Backfill Precalculated Person Properties</a>- </td>- <td>Backfill precalculated_person_properties table for realtime cohorts with person property filters</td>- </tr>- <tr class="model-backfillprecalculatedevents">- <td scope="row">- <a href="{% url 'backfill-precalculated-events' %}">Backfill Precalculated Events</a>- </td>- <td>Backfill precalculated_events table for realtime cohorts with behavioral event filters</td>- </tr><tr class="model-distinctidusage"><td scope="row"><a href="{% url 'distinct-id-usage' %}">Distinct ID usage</a>diff --git a/posthog/temporal/messaging/__init__.py b/posthog/temporal/messaging/__init__.pydeleted file mode 100644index 973a86cb40d0..000000000000--- a/posthog/temporal/messaging/__init__.py+++ /dev/null@@ -1,55 +0,0 @@-from posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow import (- BackfillPrecalculatedEventsCoordinatorWorkflow,- check_day_already_backfilled_activity,-)-from posthog.temporal.messaging.backfill_precalculated_events_workflow import (- BackfillPrecalculatedEventsWorkflow,- backfill_precalculated_events_activity,-)-from posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow import (- BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow,- get_person_id_ranges_page_activity,-)-from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (- BackfillPrecalculatedPersonPropertiesWorkflow,- backfill_precalculated_person_properties_activity,-)-from posthog.temporal.messaging.realtime_cohort_calculation_workflow import (- RealtimeCohortCalculationWorkflow,- process_realtime_cohort_calculation_activity,-)-from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- RealtimeCohortCalculationCoordinatorWorkflow,- get_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,- BackfillPrecalculatedEventsCoordinatorWorkflow,- BackfillPrecalculatedPersonPropertiesWorkflow,- BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow,- RealtimeCohortCalculationWorkflow,- RealtimeCohortCalculationCoordinatorWorkflow,- ReconcilePrecalculatedDataWorkflow,-]-ACTIVITIES = [- backfill_precalculated_events_activity,- check_day_already_backfilled_activity,- get_realtime_cohort_selection_activity,- get_query_percentile_thresholds_activity,- 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_coordinator_workflow.py b/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.pydeleted file mode 100644index ba6aee63b2ef..000000000000--- a/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.py+++ /dev/null@@ -1,273 +0,0 @@-import asyncio-import datetime as dt-import dataclasses-from typing import Any--from django.conf import settings--import temporalio.common-import temporalio.activity-import temporalio.workflow-import temporalio.exceptions--from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.messaging.backfill_precalculated_events_workflow import BackfillPrecalculatedEventsInputs-from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_client-from posthog.temporal.messaging.constants import BACKFILL_EVENT_SOURCE_PREFIX---class EventDateCheckInputs:- """Inputs for checking whether a day has already been backfilled."""-- team_id: int- condition_hashes: list[str]- date: str # YYYY-MM-DD format---class EventDateCheckResult:- """Result from checking whether a day is already backfilled."""-- date: str- already_backfilled: bool---async def check_day_already_backfilled_activity(inputs: EventDateCheckInputs) -> EventDateCheckResult:- """Check whether all conditions for a given day already have data in precalculated_events.-- This is a cheap COUNT query that catches the common re-run case without per-event lookups.- """- from posthog.clickhouse.query_tagging import Feature, Product, tags_context-- if not inputs.condition_hashes:- return EventDateCheckResult(date=inputs.date, already_backfilled=False)-- # Only rows written by the backfill count: the realtime consumer also writes to this- # table (stamped with its ingestion day), so its rows would otherwise mask days whose- # pre-cohort events were never scanned - e.g. the hours before a cohort was created.- query = """- SELECT count(DISTINCT condition) as condition_count- FROM precalculated_events- WHERE team_id = %(team_id)s- AND date = %(date)s- AND condition IN %(condition_hashes)s- AND source LIKE %(source_prefix)s- """- query_params = {- "team_id": inputs.team_id,- "date": inputs.date,- "condition_hashes": inputs.condition_hashes,- "source_prefix": f"{BACKFILL_EVENT_SOURCE_PREFIX}%",- }-- with tags_context(- team_id=inputs.team_id,- feature=Feature.BEHAVIORAL_COHORTS,- product=Product.MESSAGING,- query_type="event_backfill_day_check",- ):- async with get_messaging_client(team_id=inputs.team_id) as client:- result = await client.read_query(query, query_params)- condition_count = int(result.strip()) if result.strip() else 0-- already_backfilled = condition_count >= len(inputs.condition_hashes)- return EventDateCheckResult(date=inputs.date, already_backfilled=already_backfilled)---def compute_day_ranges(now: dt.datetime, days_to_backfill: int) -> list[tuple[dt.datetime, dt.datetime, bool]]:- """Partition the backfill window into daily [start, end, is_partial) ranges, most recent first.-- Today's range is partial: it ends at `now` rather than at the end of the day.- """- day_ranges: list[tuple[dt.datetime, dt.datetime, bool]] = []- for day_offset in range(days_to_backfill):- day_start = (now - dt.timedelta(days=day_offset)).replace(hour=0, minute=0, second=0, microsecond=0)- day_end = day_start + dt.timedelta(days=1)- is_partial = day_offset == 0- if is_partial:- day_end = now- day_ranges.append((day_start, day_end, is_partial))- return day_ranges---class BackfillPrecalculatedEventsCoordinatorInputs:- """Inputs for the coordinator workflow."""-- team_id: int- filter_storage_key: str- cohort_ids: list[int]- condition_hashes: list[str]- days_to_backfill: int- concurrent_workflows: int = 5- ignore_backfilled_dates: bool = False-- @property- def properties_to_log(self) -> dict[str, Any]:- return {- "team_id": self.team_id,- "cohort_count": len(self.cohort_ids),- "cohort_ids": self.cohort_ids,- "filter_storage_key": self.filter_storage_key,- "days_to_backfill": self.days_to_backfill,- "concurrent_workflows": self.concurrent_workflows,- "condition_count": len(self.condition_hashes),- "ignore_backfilled_dates": self.ignore_backfilled_dates,- }--[email protected](name="backfill-precalculated-events-coordinator")-class BackfillPrecalculatedEventsCoordinatorWorkflow(PostHogWorkflow):- """Coordinator workflow that partitions a time range into daily chunks- and distributes them across child workflows with concurrency control.-- Child workflow ID format: {coordinator_workflow_id}-day-{YYYY-MM-DD}- """-- @staticmethod- def parse_inputs(inputs: list[str]) -> BackfillPrecalculatedEventsCoordinatorInputs:- raise NotImplementedError("Use start_workflow() to trigger this workflow programmatically")-- async def _start_child_workflow_for_day(- self,- inputs: BackfillPrecalculatedEventsCoordinatorInputs,- workflow_logger,- day_start: dt.datetime,- day_end: dt.datetime,- child_workflow_handles: list[temporalio.workflow.ChildWorkflowHandle],- ) -> None:- date_str = day_start.strftime("%Y-%m-%d")- child_workflow_id = f"{temporalio.workflow.info().workflow_id}-day-{date_str}"- child_inputs = BackfillPrecalculatedEventsInputs(- team_id=inputs.team_id,- filter_storage_key=inputs.filter_storage_key,- cohort_ids=inputs.cohort_ids,- # ClickHouse's DateTime64 parser rejects ISO 8601 timezone suffixes (e.g. "+00:00"),- # so format the bounds in its native "YYYY-MM-DD HH:MM:SS" shape before sending to the query.- start_time=day_start.strftime("%Y-%m-%d %H:%M:%S"),- end_time=day_end.strftime("%Y-%m-%d %H:%M:%S"),- )-- child_handle = await temporalio.workflow.start_child_workflow(- "backfill-precalculated-events",- child_inputs,- id=child_workflow_id,- task_queue=settings.MESSAGING_TASK_QUEUE,- parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,- )- child_workflow_handles.append(child_handle)-- workflow_logger.info(f"Started child workflow for {date_str}")-- async def _drain_completed(- self,- done: set[temporalio.workflow.ChildWorkflowHandle],- child_workflow_handles: list[temporalio.workflow.ChildWorkflowHandle],- workflow_logger,- ) -> tuple[int, int]:- """Await completed handles and return (completed_count, failed_count) delta."""- completed = 0- failed = 0- for handle in done:- try:- await handle- completed += 1- workflow_logger.info("Child workflow completed successfully")- except Exception as e:- failed += 1- workflow_logger.exception(f"Child workflow failed: {e}")- finally:- child_workflow_handles.remove(handle)- return completed, failed-- @temporalio.workflow.run- async def run(self, inputs: BackfillPrecalculatedEventsCoordinatorInputs) -> None:- if inputs.days_to_backfill <= 0:- raise ValueError(f"days_to_backfill must be positive, got {inputs.days_to_backfill}")- if inputs.concurrent_workflows <= 0:- raise ValueError(f"concurrent_workflows must be positive, got {inputs.concurrent_workflows}")-- workflow_logger = temporalio.workflow.logger- workflow_logger.info(- f"Starting event backfill coordinator for team {inputs.team_id}: "- f"{inputs.days_to_backfill} days, {len(inputs.cohort_ids)} cohorts, "- f"{inputs.concurrent_workflows} concurrent workflows"- )-- # Compute the daily time ranges to process (most recent first for faster value delivery)- now = temporalio.workflow.now()- day_ranges = compute_day_ranges(now, inputs.days_to_backfill)-- workflow_logger.info(- f"Partitioned into {len(day_ranges)} daily chunks, "- f"from {day_ranges[-1][0].strftime('%Y-%m-%d')} to {day_ranges[0][1].strftime('%Y-%m-%d')}"- )-- child_workflow_handles: list[temporalio.workflow.ChildWorkflowHandle] = []- workflows_scheduled = 0- completed_count = 0- failed_count = 0- days_skipped = 0-- for day_start, day_end, is_partial in day_ranges:- date_str = day_start.strftime("%Y-%m-%d")-- # Check if this day is already backfilled (skippable unless ignore_backfilled_dates is set).- # Today's partial day is never skipped: existing rows only prove coverage up to an- # earlier run's start time, not up to now.- if not inputs.ignore_backfilled_dates and not is_partial:- check_result = await temporalio.workflow.execute_activity(- check_day_already_backfilled_activity,- EventDateCheckInputs(- team_id=inputs.team_id,- condition_hashes=inputs.condition_hashes,- date=date_str,- ),- start_to_close_timeout=dt.timedelta(minutes=2),- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),- )-- if check_result.already_backfilled:- workflow_logger.info(f"Skipping {date_str}: already backfilled")- days_skipped += 1- continue-- # Respect concurrency limit- if len(child_workflow_handles) >= inputs.concurrent_workflows:- done, _ = await asyncio.wait(child_workflow_handles, return_when=asyncio.FIRST_COMPLETED)- c, f = await self._drain_completed(done, child_workflow_handles, workflow_logger)- completed_count += c- failed_count += f-- await self._start_child_workflow_for_day(- inputs, workflow_logger, day_start, day_end, child_workflow_handles- )- workflows_scheduled += 1-- # Wait for all remaining child workflows- workflow_logger.info(- f"All workflows scheduled ({workflows_scheduled}), "- f"waiting for remaining {len(child_workflow_handles)}, "- f"skipped {days_skipped} already-backfilled days"- )- while child_workflow_handles:- done, _ = await asyncio.wait(child_workflow_handles, return_when=asyncio.FIRST_COMPLETED)- c, f = await self._drain_completed(done, child_workflow_handles, workflow_logger)- completed_count += c- failed_count += f-- if failed_count > 0:- workflow_logger.warning(- f"Coordinator completed with {failed_count} failed child workflows out of {workflows_scheduled} total"- )- raise temporalio.exceptions.ApplicationError(- f"{failed_count} child workflows failed; some days were not processed.",- non_retryable=False,- )-- workflow_logger.info(- f"Coordinator completed successfully for team {inputs.team_id}: "- f"processed {workflows_scheduled} days, skipped {days_skipped} already-backfilled days"- )diff --git a/posthog/temporal/messaging/backfill_precalculated_events_workflow.py b/posthog/temporal/messaging/backfill_precalculated_events_workflow.pydeleted file mode 100644index 57f41329b120..000000000000--- a/posthog/temporal/messaging/backfill_precalculated_events_workflow.py+++ /dev/null@@ -1,448 +0,0 @@-import os-import json-import time-import asyncio-import datetime as dt-import dataclasses-from typing import Any--import structlog-import temporalio.common-import temporalio.activity-import temporalio.workflow-import temporalio.exceptions-from structlog.contextvars import bind_contextvars--from posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.kafka_client.client import _KafkaProducer-from posthog.kafka_client.routing import get_producer-from posthog.kafka_client.topics import KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS-from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.heartbeat import Heartbeater-from posthog.temporal.common.logger import get_logger-from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_client-from posthog.temporal.messaging.constants import BACKFILL_EVENT_SOURCE_PREFIX-from posthog.temporal.messaging.filter_storage import get_event_filters-from posthog.temporal.messaging.types import BehavioralEventFilter--from common.hogvm.python.execute import BytecodeResult, execute_bytecode--LOGGER = get_logger(__name__)---def format_cohort_ids_for_logging(cohort_ids: list[int]) -> str:- if len(cohort_ids) > 10:- return f"More than 10... ({len(cohort_ids)} total)"- return str(cohort_ids)---def parse_event_properties(properties_raw: Any, event_uuid: str) -> dict[str, Any]:- """Parse event properties from ClickHouse, handling both string and dict formats."""- if isinstance(properties_raw, str):- try:- parsed = json.loads(properties_raw)- return parsed if isinstance(parsed, dict) else {}- except json.JSONDecodeError:- LOGGER.warning("Failed to parse properties for event", event_uuid=event_uuid)- return {}- return properties_raw if isinstance(properties_raw, dict) else {}---async def flush_kafka_batch_async(- kafka_results: list,- kafka_producer: _KafkaProducer,- team_id: int,- logger: structlog.BoundLogger,-) -> int:- """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-- 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}/{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---def evaluate_event_combined_filters_sync(- combined_bytecode: list[Any],- hog_globals: dict[str, Any],- event_uuid: str,-) -> dict[str, Any]:- """Execute combined bytecode for event filters, returning {condition_hash: result}."""- try:- bytecode_result: BytecodeResult = execute_bytecode(combined_bytecode, hog_globals)- result = bytecode_result.result- if isinstance(result, dict):- return result- return {}- except Exception as e:- LOGGER.warning(- "Failed to execute combined event filter bytecode",- event_uuid=event_uuid,- error=str(e),- )- return {}---def evaluate_event_individual_filters_sync(- filters: list[BehavioralEventFilter],- hog_globals: dict[str, Any],- event_uuid: str,-) -> dict[str, Any]:- """Execute each filter's bytecode individually for error isolation."""- results = {}- for filter_obj in filters:- try:- bytecode_result: BytecodeResult = execute_bytecode(filter_obj.bytecode, hog_globals)- result = bytecode_result.result- if isinstance(result, bool):- results[filter_obj.condition_hash] = result- except Exception as e:- LOGGER.warning(- "Failed to execute event filter bytecode",- event_uuid=event_uuid,- condition_hash=filter_obj.condition_hash,- error=str(e),- )- return results---def evaluate_event_filters_with_fallback_sync(- combined_bytecode: list[Any],- filters: list[BehavioralEventFilter],- hog_globals: dict[str, Any],- event_uuid: str,-) -> dict[str, Any]:- """Execute combined bytecode with fallback to individual filter execution."""- try:- bytecode_result: BytecodeResult = execute_bytecode(combined_bytecode, hog_globals)- result = bytecode_result.result-- if isinstance(result, dict):- invalid_entries = {k: v for k, v in result.items() if not isinstance(v, bool)}- if not invalid_entries:- return result- LOGGER.warning(- "Combined event filter evaluation returned non-boolean values, falling back",- event_uuid=event_uuid,- invalid_condition_hashes=list(invalid_entries.keys()),- )- except Exception as e:- LOGGER.info(- "Combined event filter execution failed, falling back to individual evaluation",- event_uuid=event_uuid,- error=str(e),- )-- return evaluate_event_individual_filters_sync(filters, hog_globals, event_uuid)---class BackfillPrecalculatedEventsResult:- """Result from backfilling precalculated events for a time range."""-- events_processed: int- events_produced: int- events_flushed: int- duration_seconds: float---class BackfillPrecalculatedEventsInputs:- """Inputs for the precalculated events backfill child workflow."""-- team_id: int- filter_storage_key: str- cohort_ids: list[int]- start_time: str # ISO format datetime for the start of the time range- end_time: str # ISO format datetime for the end of the time range-- @property- def properties_to_log(self) -> dict[str, Any]:- return {- "team_id": self.team_id,- "cohort_count": len(self.cohort_ids),- "cohort_ids": format_cohort_ids_for_logging(self.cohort_ids),- "filter_storage_key": self.filter_storage_key,- "start_time": self.start_time,- "end_time": self.end_time,- }---async def backfill_precalculated_events_activity(- inputs: BackfillPrecalculatedEventsInputs,-) -> BackfillPrecalculatedEventsResult:- """Scan events in a time range, evaluate behavioral bytecodes, and produce matching results to Kafka."""- bind_contextvars()- logger = LOGGER.bind(- team_id=inputs.team_id,- cohort_count=len(inputs.cohort_ids),- cohort_ids=format_cohort_ids_for_logging(inputs.cohort_ids),- )-- # Load event filters from Redis- storage_result = await asyncio.to_thread(get_event_filters, inputs.filter_storage_key)- if storage_result is None:- raise temporalio.exceptions.ApplicationError(- f"Event filters not found in storage for key: {inputs.filter_storage_key}. "- "The Redis payload may have expired; please re-store the filters and restart the workflow.",- type="MissingFilters",- non_retryable=True,- )-- filters, event_names, combined_bytecodes_by_event = storage_result- logger.info(f"Loaded {len(filters)} event filters for {len(event_names)} event names from storage")-- if not filters:- logger.info("No event filters found, aborting backfill")- return BackfillPrecalculatedEventsResult(- events_processed=0, events_produced=0, events_flushed=0, duration_seconds=0.0- )-- # Build a lookup from event_name to its filters for fallback evaluation- filters_by_event: dict[str, list[BehavioralEventFilter]] = {}- for f in filters:- filters_by_event.setdefault(f.event_name, []).append(f)-- logger.info(- f"Starting event backfill for time range {inputs.start_time} to {inputs.end_time}, "- f"scanning {len(event_names)} event names: {event_names}"- )-- async with Heartbeater(- details=(f"Processing events from {inputs.start_time} to {inputs.end_time}",)- ) as heartbeater:- start_time = time.time()- kafka_producer = get_producer(topic=KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS)-- total_processed = 0- total_events_produced = 0- total_flushed = 0- kafka_results: list = []- try:- KAFKA_FLUSH_BATCH_SIZE = int(os.environ.get("BACKFILL_EVENTS_KAFKA_FLUSH_BATCH_SIZE", "1000"))- except ValueError:- 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- 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.timestamp- FORMAT JSONEachRow- """-- query_params = {- "team_id": inputs.team_id,- "event_names": event_names,- "start_time": inputs.start_time,- "end_time": inputs.end_time,- }-- with tags_context(- team_id=inputs.team_id,- feature=Feature.BEHAVIORAL_COHORTS,- product=Product.MESSAGING,- query_type="event_backfill",- ):- query_start_time = time.monotonic()- first_row = True-- async with get_messaging_client(team_id=inputs.team_id) as client:- async for row in client.stream_query_as_jsonl(events_query, query_parameters=query_params):- if first_row:- time_to_first = time.monotonic() - query_start_time- logger.info(- "First row received from ClickHouse",- time_to_first_row_seconds=round(time_to_first, 2),- )- first_row = False-- total_processed += 1- event_uuid = str(row["uuid"])- event_name = row["event"]- event_date = str(row["date"])- distinct_id = str(row["distinct_id"])- person_id = str(row["person_id"])- event_properties = parse_event_properties(row["properties"], event_uuid)-- # Look up the combined bytecode for this event name- combined_bytecode = combined_bytecodes_by_event.get(event_name)- event_filters = filters_by_event.get(event_name, [])-- if not combined_bytecode and not event_filters:- continue-- # Build HogVM globals for event evaluation- hog_globals = {"event": event_name, "properties": event_properties}-- if combined_bytecode:- filter_results = await asyncio.to_thread(- evaluate_event_filters_with_fallback_sync,- combined_bytecode,- event_filters,- hog_globals,- event_uuid,- )- else:- filter_results = await asyncio.to_thread(- evaluate_event_individual_filters_sync,- event_filters,- hog_globals,- event_uuid,- )-- # Produce Kafka messages for matching conditions- for condition_hash, matches in filter_results.items():- if matches:- try:- produce_result = await asyncio.to_thread(- kafka_producer.produce,- topic=KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,- data={- "uuid": event_uuid,- "team_id": inputs.team_id,- "person_id": person_id,- "distinct_id": distinct_id,- "condition": condition_hash,- "date": event_date,- "source": f"{BACKFILL_EVENT_SOURCE_PREFIX}_{condition_hash}",- },- )- kafka_results.append(produce_result)- total_events_produced += 1- except Exception as e:- logger.warning(- f"Failed to produce Kafka message for event {event_uuid}: {e}",- event_uuid=event_uuid,- condition_hash=condition_hash,- error=str(e),- )-- # Periodically flush Kafka- if len(kafka_results) >= KAFKA_FLUSH_BATCH_SIZE:- batch_flushed = await flush_kafka_batch_async(- kafka_results, kafka_producer, inputs.team_id, logger- )- total_flushed += batch_flushed- kafka_results.clear()-- # Update heartbeat periodically- if total_processed % 10000 == 0:- heartbeater.details = (- f"Processed {total_processed} events, produced {total_events_produced}, "- f"pending {len(kafka_results)} messages",- )-- # Final flush- if kafka_results:- logger.info(f"Final flush of {len(kafka_results)} Kafka results")- final_flushed = await flush_kafka_batch_async(kafka_results, kafka_producer, inputs.team_id, logger)- total_flushed += final_flushed-- duration_seconds = time.time() - start_time-- logger.info(- f"Completed event backfill for {inputs.start_time} to {inputs.end_time}: "- f"processed {total_processed} events, produced {total_events_produced}, "- f"flushed {total_flushed} in {duration_seconds:.1f}s",- )-- return BackfillPrecalculatedEventsResult(- events_processed=total_processed,- events_produced=total_events_produced,- events_flushed=total_flushed,- duration_seconds=duration_seconds,- )--[email protected](name="backfill-precalculated-events")-class BackfillPrecalculatedEventsWorkflow(PostHogWorkflow):- """Child workflow that backfills precalculated events for a single time range."""-- @staticmethod- def parse_inputs(inputs: list[str]) -> BackfillPrecalculatedEventsInputs:- raise NotImplementedError("Use start_workflow() to trigger this workflow programmatically")-- @temporalio.workflow.run- async def run(self, inputs: BackfillPrecalculatedEventsInputs) -> BackfillPrecalculatedEventsResult:- workflow_logger = temporalio.workflow.logger- workflow_logger.info(- f"Starting event backfill for {len(inputs.cohort_ids)} cohorts "- f"(team {inputs.team_id}, range: {inputs.start_time} to {inputs.end_time})"- )-- result = await temporalio.workflow.execute_activity(- backfill_precalculated_events_activity,- inputs,- start_to_close_timeout=dt.timedelta(hours=12),- heartbeat_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=3,- initial_interval=dt.timedelta(seconds=10),- maximum_interval=dt.timedelta(minutes=1),- ),- )-- workflow_logger.info(- f"Completed event backfill: processed {result.events_processed} events, "- f"produced {result.events_produced}, flushed {result.events_flushed} "- f"(range: {inputs.start_time} to {inputs.end_time})"- )-- return resultdiff --git a/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py b/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.pydeleted file mode 100644index d25adee1e097..000000000000--- a/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py+++ /dev/null@@ -1,345 +0,0 @@-import asyncio-import datetime as dt-import dataclasses-from typing import Any--from django.conf import settings--import temporalio.common-import temporalio.activity-import temporalio.workflow-import temporalio.exceptions--from posthog.hogql import ast--from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (- BackfillPrecalculatedPersonPropertiesInputs,-)-from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_client-from posthog.temporal.messaging.hogql_compile import compile_hogql_for_streaming---def _combine_where(exprs: list[ast.Expr]) -> ast.Expr | None:- """Combine a list of WHERE expressions with AND, or return None for an empty list."""- if not exprs:- return None- if len(exprs) == 1:- return exprs[0]- return ast.And(exprs=exprs)---class PersonIdRangesPageInputs:- """Inputs for fetching a page of person ID ranges."""-- team_id: int- batch_size: int # persons per range- page_size: int # number of ranges to return per page- after_person_id: str | None # cursor: fetch persons with ID > this value, None for first page- person_id: str | None = None # Optional specific person ID to filter for---class PersonIdRangesPageResult:- """Result from fetching a page of person ID ranges."""-- ranges: list[tuple[str, str]] # (start_id, end_id) pairs- cursor: str | None # last person ID in this page, None if no more data---async def get_person_id_ranges_page_activity(inputs: PersonIdRangesPageInputs) -> PersonIdRangesPageResult:- """Fetch a page of person ID ranges for a team using cursor-based pagination."""- from posthog.clickhouse.query_tagging import Feature, Product, tags_context-- if inputs.batch_size <= 0:- raise ValueError(f"batch_size must be positive, got {inputs.batch_size}")- if inputs.page_size <= 0:- raise ValueError(f"page_size must be positive, got {inputs.page_size}")-- limit = inputs.batch_size * inputs.page_size- # Fetch one extra row to check if there's more data- query_limit = limit + 1-- where_exprs: list[ast.Expr] = []- if inputs.after_person_id is not None:- where_exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.Gt,- left=ast.Field(chain=["id"]),- right=ast.Constant(value=inputs.after_person_id),- )- )- if inputs.person_id is not None:- where_exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.Eq,- left=ast.Field(chain=["id"]),- right=ast.Constant(value=inputs.person_id),- )- )-- # Enumerate person IDs straight off the raw ``person`` table with DISTINCT, not the ``persons``- # lazy table. We only need ID range *boundaries* here, not deduplicated / is_deleted-filtered- # rows -- the child workflow re-queries each range against ``raw_persons`` via ``argmax_select``- # with full argMax dedup and is_deleted filtering, so a deleted/duplicate ID slipping into a- # boundary just yields no child rows. Going through the ``persons`` lazy table would instead- # rewrite our ``id > cursor`` cursor filter into an unbounded ``id IN (subquery)`` with a full- # per-page dedup over the entire ID tail -- O(pages x tail). The direct ``SELECT DISTINCT id ...- # ORDER BY id LIMIT N`` reads the ``(team_id, id)`` primary key in order and stops after N IDs.- ranges_query_ast = ast.SelectQuery(- select=[ast.Alias(alias="person_id", expr=ast.Field(chain=["id"]))],- distinct=True,- select_from=ast.JoinExpr(table=ast.Field(chain=["raw_persons"])),- where=_combine_where(where_exprs),- order_by=[ast.OrderExpr(expr=ast.Field(chain=["id"]), order="ASC")],- limit=ast.Constant(value=query_limit),- )-- query, query_params = await compile_hogql_for_streaming(ranges_query_ast, team_id=inputs.team_id)-- ranges: list[tuple[str, str]] = []- current_batch_start: str | None = None- current_batch_count = 0- total_count = 0- last_person_id: str | None = None- has_more_data = False-- with tags_context(- team_id=inputs.team_id,- feature=Feature.BEHAVIORAL_COHORTS,- product=Product.MESSAGING,- query_type="person_id_ranges_page",- ):- async with get_messaging_client(team_id=inputs.team_id) as client:- async for row in client.stream_query_as_jsonl(query, query_parameters=query_params):- person_id = str(row["person_id"])-- # If we hit the limit + 1, we know there's more data, but don't process this row- if total_count >= limit:- has_more_data = True- break-- last_person_id = person_id-- if current_batch_start is None:- current_batch_start = person_id- current_batch_count = 1- else:- current_batch_count += 1-- total_count += 1-- if current_batch_count >= inputs.batch_size:- ranges.append((current_batch_start, person_id))- current_batch_start = None- current_batch_count = 0- # Heartbeat after each completed range to ensure regular heartbeats- temporalio.activity.heartbeat(f"Page: processed {total_count} persons, {len(ranges)} ranges")-- # Handle final partial batch- if current_batch_start is not None and current_batch_count > 0 and last_person_id is not None:- ranges.append((current_batch_start, last_person_id))-- # Final heartbeat to report completion- if total_count > 0:- temporalio.activity.heartbeat(f"Page: processed {total_count} persons, {len(ranges)} ranges")-- # Set cursor only if we know there's more data- cursor = last_person_id if has_more_data else None-- return PersonIdRangesPageResult(ranges=ranges, cursor=cursor)---class BackfillPrecalculatedPersonPropertiesCoordinatorInputs:- """Inputs for the coordinator workflow using ID-range based batching."""-- team_id: int- filter_storage_key: str # Redis key containing the filters- cohort_ids: list[int] # All cohort IDs being processed- batch_size: int = 1000 # Persons per batch- concurrent_workflows: int = 5 # Number of concurrent workflows to run- person_id: str | None = None # Optional specific person ID to filter for- single_cohort_mode: bool = False # True when --cohort-id was explicitly provided-- @property- def properties_to_log(self) -> dict[str, Any]:- return {- "team_id": self.team_id,- "cohort_count": len(self.cohort_ids),- "cohort_ids": self.cohort_ids,- "filter_storage_key": self.filter_storage_key,- "batch_size": self.batch_size,- "concurrent_workflows": self.concurrent_workflows,- }--[email protected](name="backfill-precalculated-person-properties-coordinator")-class BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow(PostHogWorkflow):- """Coordinator workflow that processes persons using ID-range based batching.-- First fetches all person IDs for the team, then splits them into ranges- and processes multiple ranges concurrently using child workflows.- This approach provides better parallelism and predictable batch sizes.-- Child workflow ID format: {coordinator_workflow_id}-batch-{batch_number}- """-- @staticmethod- def parse_inputs(inputs: list[str]) -> BackfillPrecalculatedPersonPropertiesCoordinatorInputs:- """Parse inputs from the management command CLI."""- raise NotImplementedError("Use start_workflow() to trigger this workflow programmatically")-- async def _start_child_workflow_for_range(- self,- inputs: BackfillPrecalculatedPersonPropertiesCoordinatorInputs,- workflow_logger,- batch_number: int,- start_person_id: str,- end_person_id: str,- child_workflow_handles: list[temporalio.workflow.ChildWorkflowHandle],- ) -> None:- """Helper to start a child workflow for a person ID range."""- child_workflow_id = f"{temporalio.workflow.info().workflow_id}-batch-{batch_number}"- child_inputs = BackfillPrecalculatedPersonPropertiesInputs(- team_id=inputs.team_id,- filter_storage_key=inputs.filter_storage_key,- cohort_ids=inputs.cohort_ids,- batch_size=inputs.batch_size,- start_person_id=start_person_id,- end_person_id=end_person_id,- person_id=inputs.person_id,- single_cohort_mode=inputs.single_cohort_mode,- )-- # Start child workflow- child_handle = await temporalio.workflow.start_child_workflow(- "backfill-precalculated-person-properties",- child_inputs,- id=child_workflow_id,- task_queue=settings.MESSAGING_TASK_QUEUE,- parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,- )- child_workflow_handles.append(child_handle)-- workflow_logger.info(- f"Started batch {batch_number}: processing person IDs {start_person_id} to {end_person_id}"- )-- async def _drain_completed(- self,- done: set[temporalio.workflow.ChildWorkflowHandle],- child_workflow_handles: list[temporalio.workflow.ChildWorkflowHandle],- workflow_logger,- ) -> tuple[int, int]:- """Await completed handles and return (completed_count, failed_count) delta."""- completed = 0- failed = 0- for handle in done:- try:- await handle- completed += 1- workflow_logger.info("Child workflow completed successfully")- except Exception as e:- failed += 1- workflow_logger.exception(f"Child workflow failed: {e}")- finally:- child_workflow_handles.remove(handle)- return completed, failed-- @temporalio.workflow.run- async def run(self, inputs: BackfillPrecalculatedPersonPropertiesCoordinatorInputs) -> None:- """Run the coordinator workflow using paginated ID-range discovery.-- Fetches person ID ranges page by page and starts child workflows as- ranges are discovered, respecting the concurrency limit throughout.- """- if inputs.batch_size <= 0:- raise ValueError(f"batch_size must be positive, got {inputs.batch_size}")- if inputs.concurrent_workflows <= 0:- raise ValueError(f"concurrent_workflows must be positive, got {inputs.concurrent_workflows}")-- workflow_logger = temporalio.workflow.logger- cohort_ids = inputs.cohort_ids- workflow_logger.info(- f"Starting person properties precalculation coordinator for {len(cohort_ids)} cohorts "- f"(team {inputs.team_id}, cohorts {cohort_ids}) with {inputs.concurrent_workflows} concurrent workflows"- )-- child_workflow_handles: list[temporalio.workflow.ChildWorkflowHandle] = []- batch_number = 0- workflows_scheduled = 0- completed_count = 0- failed_count = 0- cursor: str | None = None- has_more = True-- while has_more:- page = await temporalio.workflow.execute_activity(- get_person_id_ranges_page_activity,- PersonIdRangesPageInputs(- team_id=inputs.team_id,- batch_size=inputs.batch_size,- page_size=inputs.concurrent_workflows,- after_person_id=cursor,- person_id=inputs.person_id,- ),- start_to_close_timeout=dt.timedelta(minutes=10),- heartbeat_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),- )-- if not page.ranges:- if batch_number == 0:- workflow_logger.info("No persons found for team, nothing to process")- break-- workflow_logger.info(- f"Fetched page with {len(page.ranges)} ranges "- f"(cursor: {cursor} -> {page.cursor}, total batches so far: {batch_number})"- )-- for start_person_id, end_person_id in page.ranges:- batch_number += 1-- # Respect concurrency limit - wait for a slot before starting- if len(child_workflow_handles) >= inputs.concurrent_workflows:- done, _ = await asyncio.wait(child_workflow_handles, return_when=asyncio.FIRST_COMPLETED)- c, f = await self._drain_completed(done, child_workflow_handles, workflow_logger)- completed_count += c- failed_count += f-- await self._start_child_workflow_for_range(- inputs, workflow_logger, batch_number, start_person_id, end_person_id, child_workflow_handles- )- workflows_scheduled += 1-- cursor = page.cursor- if cursor is None:- has_more = False-- # Wait for all remaining child workflows- workflow_logger.info(- f"All workflows scheduled ({workflows_scheduled}), waiting for remaining {len(child_workflow_handles)}"- )- while child_workflow_handles:- done, _ = await asyncio.wait(child_workflow_handles, return_when=asyncio.FIRST_COMPLETED)- c, f = await self._drain_completed(done, child_workflow_handles, workflow_logger)- completed_count += c- failed_count += f-- if failed_count > 0:- workflow_logger.warning(- f"Coordinator completed with {failed_count} failed child workflows out of {workflows_scheduled} total"- )- raise temporalio.exceptions.ApplicationError(- f"{failed_count} child workflows failed; some person ID ranges were not processed.",- non_retryable=False,- )-- workflow_logger.info(- f"Coordinator workflow completed successfully for team {inputs.team_id}: "- f"processed {batch_number} ranges with {inputs.concurrent_workflows} concurrent workflows"- )diff --git a/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py b/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.pydeleted file mode 100644index 6581d094a55c..000000000000--- a/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py+++ /dev/null@@ -1,809 +0,0 @@-import os-import json-import time-import asyncio-import datetime as dt-import dataclasses-from typing import TYPE_CHECKING, Any--import structlog-import temporalio.common-import temporalio.activity-import temporalio.workflow-import temporalio.exceptions-from structlog.contextvars import bind_contextvars--from posthog.hogql import ast-from posthog.hogql.constants import HogQLQuerySettings-from posthog.hogql.database.argmax import argmax_select--from posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.kafka_client.client import _KafkaProducer-from posthog.kafka_client.routing import get_producer-from posthog.kafka_client.topics import KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES-from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.heartbeat import Heartbeater-from posthog.temporal.common.logger import get_logger-from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_client-from posthog.temporal.messaging.filter_storage import get_filters_and_properties-from posthog.temporal.messaging.hogql_compile import compile_hogql_for_streaming-from posthog.temporal.messaging.types import PersonPropertyFilter--from common.hogvm.python.execute import BytecodeResult, execute_bytecode--if TYPE_CHECKING:- pass--LOGGER = get_logger(__name__)-MAX_OPTIMIZED_PROPERTIES = 100 # Safety limit to avoid query complexity issues--# Alias for the full ``properties`` JSON column in the fallback query. It doubles as the format-# discriminator for the row consumer: its presence in a row selects the fallback path. Producer and-# consumer must use this same constant so they move together.-FULL_PROPERTIES_KEY = "properties"---def build_person_properties_select_fields(- person_properties: list[str],-) -> tuple[dict[str, list[str | int]], dict[str, str]]:- """Map each requested person property to an ``argmax_select`` field chain and its ``prop_N`` alias.-- Property names come from cohort filters, so they must never be substring-concatenated into SQL.- Returning ``["properties", key]`` field chains keeps each key inside an ``ast.Field`` chain when- ``argmax_select`` wraps it in the per-person ``argMax`` aggregation: HogQL either rewrites to a- materialized column or routes the key through context parameters when emitting ``JSONExtract``.- """- select_fields: dict[str, list[str | int]] = {}- alias_mapping: dict[str, str] = {}-- for i, prop in enumerate(person_properties):- alias = f"prop_{i}"- select_fields[alias] = ["properties", prop]- alias_mapping[alias] = prop-- return select_fields, alias_mapping---def format_cohort_ids_for_logging(cohort_ids: list[int]) -> str:- """Format cohort IDs for logging, showing simplified text for large sets.-- Args:- cohort_ids: List of cohort IDs-- Returns:- String representation of cohort IDs, or simplified text if too many- """- if len(cohort_ids) > 10:- return f"More than 10... ({len(cohort_ids)} total)"- else:- return str(cohort_ids)---def parse_person_properties(properties_raw: Any, person_id: str) -> dict[str, Any]:- """Parse person properties from ClickHouse, handling both string and dict formats.-- Args:- properties_raw: The raw properties value from ClickHouse (can be string, dict, or None)- person_id: The person ID for logging purposes-- Returns:- A dictionary of person properties (empty dict if parsing fails or non-dict value)- """- if isinstance(properties_raw, str):- try:- parsed = json.loads(properties_raw)- # Ensure we only return dicts (handles null, numbers, arrays, etc.)- return parsed if isinstance(parsed, dict) else {}- except json.JSONDecodeError:- LOGGER.warning("Failed to parse properties for person", person_id=person_id)- return {}- else:- return properties_raw if isinstance(properties_raw, dict) else {}---async def flush_kafka_batch_async(- kafka_results: list,- kafka_producer: _KafkaProducer,- team_id: int,- logger: structlog.BoundLogger,- flush_duration_metric=None,-) -> int:- """Flush Kafka messages asynchronously and return count of successful messages.-- Args:- kafka_results: List of ProduceResult objects from Kafka send operations- kafka_producer: Kafka producer instance- team_id: Team ID for logging- logger: Logger instance- flush_duration_metric: Optional metric to record flush duration-- Returns:- Number of successfully processed messages- """- if not kafka_results:- return 0-- # Count the successful produce results- successful_count = len(kafka_results) # All results in the list are successful ones-- # Time the Kafka flush operation for performance monitoring- flush_start_time = time.monotonic()- await asyncio.to_thread(kafka_producer.flush)- flush_duration = time.monotonic() - flush_start_time-- # Record flush performance metrics if metric is provided- if flush_duration_metric:- flush_duration_metric.record(flush_duration, {"team_id": str(team_id)})-- logger.info(- f"Async flushed batch in {flush_duration:.3f}s: {successful_count} successful messages",- team_id=team_id,- successful_messages=successful_count,- total_messages=len(kafka_results),- flush_duration_seconds=flush_duration,- )-- return successful_count---def get_person_properties_backfill_success_metric():- """Counter for successful person properties backfills."""- return temporalio.activity.metric_meter().create_counter(- "person_properties_backfill_success", "Number of successful person properties backfills"- )---def get_person_properties_backfill_failure_metric():- """Counter for failed person properties backfills."""- return temporalio.activity.metric_meter().create_counter(- "person_properties_backfill_failure", "Number of failed person properties backfills"- )---def get_query_duration_metric():- """Histogram for ClickHouse query durations."""- return temporalio.activity.metric_meter().create_histogram_float(- "backfill_clickhouse_query_duration_seconds", "Duration of ClickHouse queries in seconds", unit="seconds"- )---def get_person_processing_rate_metric():- """Gauge for person processing rate."""- return temporalio.activity.metric_meter().create_histogram_float(- "backfill_person_processing_rate", "Persons processed per second", unit="persons/second"- )---def get_filter_evaluation_duration_metric():- """Histogram for filter evaluation durations."""- return temporalio.activity.metric_meter().create_histogram_float(- "backfill_filter_evaluation_duration_seconds", "Duration of filter evaluations in seconds", unit="seconds"- )---def get_flush_duration_metric():- """Histogram for Kafka flush durations."""- return temporalio.activity.metric_meter().create_histogram_float(- "backfill_kafka_flush_duration_seconds", "Duration of Kafka flush operations in seconds", unit="seconds"- )---class CohortFilters:- """Filters for a specific cohort."""-- cohort_id: int- filters: list[PersonPropertyFilter]---class BackfillPrecalculatedPersonPropertiesResult:- """Result from backfilling precalculated person properties."""-- persons_processed: int- events_produced: int- events_flushed: int- last_person_id: str | None # None if no persons were processed- duration_seconds: float---class BackfillPrecalculatedPersonPropertiesInputs:- """Inputs for the precalculated person properties backfill workflow."""-- team_id: int- filter_storage_key: str # Redis key containing the filters- cohort_ids: list[int] # All cohort IDs being processed- batch_size: int = 1000- start_person_id: str = "00000000-0000-0000-0000-000000000000" # Starting person ID for this batch- end_person_id: str = "ffffffff-ffff-ffff-ffff-ffffffffffff" # Ending person ID for this batch- person_id: str | None = None # Optional specific person ID to filter for- single_cohort_mode: bool = False # True when --cohort-id was explicitly provided-- @property- def properties_to_log(self) -> dict[str, Any]:- return {- "team_id": self.team_id,- "cohort_count": len(self.cohort_ids),- "cohort_ids": format_cohort_ids_for_logging(self.cohort_ids),- "filter_storage_key": self.filter_storage_key,- "batch_size": self.batch_size,- "start_person_id": self.start_person_id,- "end_person_id": self.end_person_id,- }---def evaluate_combined_filters_sync(- combined_bytecode: list[Any],- hog_globals: dict[str, Any],- person_id: str,- detailed_logging: bool = False,-) -> dict[str, Any]:- """Execute combined bytecode for all filters, returning {condition_hash: result}.-- Returns empty dict on error so the person is skipped without crashing the activity.- """- try:- bytecode_result: BytecodeResult = execute_bytecode(combined_bytecode, hog_globals)- result = bytecode_result.result-- if detailed_logging:- LOGGER.info(- "HogVM evaluation completed",- person_id=person_id,- result=result,- result_type=type(result).__name__,- person_properties=hog_globals.get("person", {}).get("properties", {}),- execution_successful=True,- execution_stdout=bytecode_result.stdout,- )-- if isinstance(result, dict):- return result-- if detailed_logging:- LOGGER.warning(- "HogVM evaluation returned non-dict result",- person_id=person_id,- result=result,- result_type=type(result).__name__,- )-- return {}- except Exception as e:- LOGGER.warning(- "Failed to execute combined filter bytecode for person",- person_id=person_id,- error=str(e),- )- return {}---def evaluate_individual_filters_sync(- filters: list[PersonPropertyFilter],- hog_globals: dict[str, Any],- person_id: str,- detailed_logging: bool = False,-) -> dict[str, Any]:- """Execute each filter's bytecode individually, returning {condition_hash: result}.-- Isolates failures to individual cohorts rather than failing all cohorts for a person.- Returns results for successful filters only; failed filters are omitted from results.- """- results = {}-- for filter_obj in filters:- try:- bytecode_result: BytecodeResult = execute_bytecode(filter_obj.bytecode, hog_globals)- result = bytecode_result.result-- if detailed_logging:- LOGGER.info(- "Individual filter evaluation completed",- person_id=person_id,- condition_hash=filter_obj.condition_hash,- result=result,- result_type=type(result).__name__,- execution_successful=True,- execution_stdout=bytecode_result.stdout,- )-- # Store the result for this specific condition- if isinstance(result, bool):- results[filter_obj.condition_hash] = result- elif detailed_logging:- LOGGER.warning(- "Individual filter evaluation returned non-bool result",- person_id=person_id,- condition_hash=filter_obj.condition_hash,- result=result,- result_type=type(result).__name__,- )- except Exception as e:- LOGGER.warning(- "Failed to execute filter bytecode for person",- person_id=person_id,- condition_hash=filter_obj.condition_hash,- cohort_ids=filter_obj.cohort_ids,- error=str(e),- )-- return results---def evaluate_combined_filters_with_fallback_sync(- combined_bytecode: list[Any],- filters: list[PersonPropertyFilter],- hog_globals: dict[str, Any],- person_id: str,- detailed_logging: bool = False,-) -> dict[str, Any]:- """Execute combined bytecode with fallback to individual filter execution.-- First attempts to execute all filters in a single combined bytecode for performance.- If that fails, falls back to executing each filter individually to isolate failures.- """- # First, try the fast path with combined bytecode- try:- bytecode_result: BytecodeResult = execute_bytecode(combined_bytecode, hog_globals)- result = bytecode_result.result-- if detailed_logging:- LOGGER.info(- "Combined filter evaluation completed successfully",- person_id=person_id,- result=result,- result_type=type(result).__name__,- person_properties=hog_globals.get("person", {}).get("properties", {}),- execution_successful=True,- execution_stdout=bytecode_result.stdout,- )-- if isinstance(result, dict):- invalid_result_entries = {- condition_hash: value for condition_hash, value in result.items() if not isinstance(value, bool)- }- if not invalid_result_entries:- return result- LOGGER.warning(- "Combined filter evaluation returned non-boolean values, falling back to individual execution",- person_id=person_id,- invalid_condition_hashes=list(invalid_result_entries.keys()),- invalid_result_types={- condition_hash: type(value).__name__ for condition_hash, value in invalid_result_entries.items()- },- )-- if detailed_logging:- LOGGER.warning(- "Combined filter evaluation returned non-dict result, falling back to individual execution",- person_id=person_id,- result=result,- result_type=type(result).__name__,- )- except Exception as e:- LOGGER.info(- "Combined filter execution failed, falling back to individual filter evaluation",- person_id=person_id,- error=str(e),- fallback_reason="combined_execution_failed",- )-- # Fallback to individual filter execution for error isolation- return evaluate_individual_filters_sync(filters, hog_globals, person_id, detailed_logging)---async def backfill_precalculated_person_properties_activity(- inputs: BackfillPrecalculatedPersonPropertiesInputs,-) -> BackfillPrecalculatedPersonPropertiesResult:- """- Backfill precalculated person properties for a batch of persons across multiple cohorts.-- Queries the current state of persons from the persons table and evaluates them- against all provided filters from multiple cohorts, writing results to the- precalculated_person_properties table. Each person is evaluated against all filters- from all cohorts in a single pass for efficiency.- """- bind_contextvars()- cohort_ids = inputs.cohort_ids- logger = LOGGER.bind(- team_id=inputs.team_id, cohort_count=len(cohort_ids), cohort_ids=format_cohort_ids_for_logging(cohort_ids)- )-- # Load filters, person properties, and combined bytecode from Redis storage without blocking the event loop- storage_result = await asyncio.to_thread(get_filters_and_properties, inputs.filter_storage_key)- if storage_result is None:- raise temporalio.exceptions.ApplicationError(- f"Filters not found in storage for key: {inputs.filter_storage_key}. "- "The Redis payload may have expired; please re-store the filters and restart the workflow.",- type="MissingFilters",- non_retryable=True,- )-- filters, person_properties, combined_bytecode = storage_result- logger.info(f"Loaded {len(filters)} filters from storage key: {inputs.filter_storage_key}")-- # Early abort if no filters to process- if not filters:- logger.info("No filters found for real-time cohorts, aborting backfill")- return BackfillPrecalculatedPersonPropertiesResult(- persons_processed=0,- events_produced=0,- events_flushed=0,- last_person_id=None,- duration_seconds=0.0,- )-- if person_properties:- logger.info(f"Detected {len(person_properties)} unique person properties in use: {person_properties}")- else:- logger.info("No person properties detected or using legacy storage format")-- logger.info(- f"Starting person properties precalculation for {len(cohort_ids)} cohorts {format_cohort_ids_for_logging(cohort_ids)}, "- f"processing {len(filters)} total filters from person ID {inputs.start_person_id} to {inputs.end_person_id} "- f"with batch size {inputs.batch_size} ({len(filters)} filters = ~{inputs.batch_size * len(filters)} events per batch)"- )-- # Enable detailed logging when both cohort_id and person_id are set (single cohort + single person mode)- detailed_logging_enabled = inputs.person_id is not None and inputs.single_cohort_mode-- async with Heartbeater(- details=(f"Processing persons from {inputs.start_person_id} to {inputs.end_person_id}",)- ) as heartbeater:- start_time = time.time()- kafka_producer = get_producer(topic=KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES)-- total_processed = 0- total_events_produced = 0- total_flushed = 0- # Use batched Kafka flushing to avoid memory buildup and reduce data loss risk- kafka_results = [] # Store ProduceResult objects for periodic flushing- KAFKA_FLUSH_BATCH_SIZE = int(- os.environ.get("BACKFILL_KAFKA_FLUSH_BATCH_SIZE", "1000")- ) # Configurable flush size-- # Create metrics once for activity- query_duration_metric = None- person_processing_rate_metric = None- filter_evaluation_duration_metric = None- try:- metric_meter = temporalio.activity.metric_meter()- query_duration_metric = metric_meter.create_histogram_float(- "backfill_clickhouse_query_duration_seconds",- "Duration of ClickHouse queries in seconds",- unit="seconds",- )- person_processing_rate_metric = metric_meter.create_histogram_float(- "backfill_person_processing_rate", "Persons processed per second", unit="persons/second"- )- filter_evaluation_duration_metric = metric_meter.create_histogram_float(- "backfill_filter_evaluation_duration_seconds",- "Duration of filter evaluations in seconds",- unit="seconds",- )- except RuntimeError:- # Not in activity context (e.g., during tests), skip metrics- pass-- # Build the per-property argmax_select fields — either targeted property accessors (so HogQL- # can use materialized columns when present) or the full ``properties`` JSON as a fallback.- property_alias_mapping: dict[str, str] = {}- select_fields: dict[str, list[str | int]] = {}-- # A '%' in a property key makes the HogQL printer raise (it can resolve the accessor to a- # column identifier, and '%' is banned there). Such keys are rare but valid person-property- # names, so when any appear we fall back to fetching the full ``properties`` JSON: the- # consumer evaluates filters against the full dict regardless, which keeps these keys working.- has_identifier_unsafe_key = any("%" in prop for prop in person_properties)-- if person_properties and len(person_properties) <= MAX_OPTIMIZED_PROPERTIES and not has_identifier_unsafe_key:- select_fields, property_alias_mapping = build_person_properties_select_fields(person_properties)-- logger.info(f"Optimized query: fetching {len(person_properties)} specific properties via HogQL")- else:- # Emitting the full ``properties`` column also flags this row as fallback-format: the- # consumer below keys on ``FULL_PROPERTIES_KEY`` to take the fallback path instead of- # reconstructing the dict from per-property ``prop_N`` columns.- select_fields[FULL_PROPERTIES_KEY] = [FULL_PROPERTIES_KEY]- if person_properties and len(person_properties) > MAX_OPTIMIZED_PROPERTIES:- logger.warning(- f"Too many properties ({len(person_properties)} > {MAX_OPTIMIZED_PROPERTIES}) - falling back to fetching all properties for performance"- )- elif has_identifier_unsafe_key:- logger.warning(- "Property key contains '%' (not a valid HogQL identifier) - falling back to fetching all properties"- )- else:- logger.warning(- "Falling back to fetching all properties - could not determine specific properties needed"- )-- # These predicates are set as a direct ``WHERE`` on the argMax aggregation below, so they- # apply *before* dedup. They must stay id-only (``id`` is the GROUP BY key, so filtering on it- # yields the same rows pre- and post-dedup). Adding a non-id predicate here (e.g. a- # ``properties.x`` filter) would match raw pre-dedup rows and quietly select the wrong persons.- where_exprs: list[ast.Expr] = [- ast.CompareOperation(- op=ast.CompareOperationOp.GtEq,- left=ast.Field(chain=["id"]),- right=ast.Constant(value=inputs.start_person_id),- ),- ast.CompareOperation(- op=ast.CompareOperationOp.LtEq,- left=ast.Field(chain=["id"]),- right=ast.Constant(value=inputs.end_person_id),- ),- ]- if inputs.person_id is not None:- where_exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.Eq,- left=ast.Field(chain=["id"]),- right=ast.Constant(value=inputs.person_id),- )- )-- # Deduplicate straight off the raw ``person`` table with ``argmax_select`` instead of the- # ``persons`` lazy table. ``argmax_select`` is the exact helper the ``persons`` table uses- # internally, so the semantics are identical: ``team_id`` scoping (added by the printer),- # latest-version-per-id dedup, ``is_deleted = 0`` filtering, and the- # ``argMax(created_at) < now() + 1 day`` clamp that drops future-dated persons. The win: going- # straight to ``raw_persons`` avoids the ``persons`` lazy table rewriting our ID-range filter- # into an ``id IN (subquery)`` that scans the range twice; the direct ``WHERE`` reads the- # ``(team_id, id)`` primary key once.- # Output column for the person UUID is ``id`` (argmax_select aliases the group field by name).- persons_query_ast = argmax_select(- table_name="raw_persons",- select_fields=select_fields,- group_fields=["id"],- argmax_field="version",- deleted_field="is_deleted",- timestamp_field_to_clamp="created_at",- )- persons_query_ast.where = ast.And(exprs=where_exprs)- persons_query_ast.order_by = [ast.OrderExpr(expr=ast.Field(chain=["id"]), order="ASC")]- # optimize_aggregation_in_order lets ClickHouse aggregate as it streams the primary key in- # order, so the GROUP BY + ORDER BY id never buffers the whole range. No explicit limit:- # compile_hogql_for_streaming uses LimitContext.COHORT_CALCULATION (LIMIT 1_000_000_000), and- # ID ranges are bounded by batch_size (default 1000 persons), so the cap is never reached.- persons_query_ast.settings = HogQLQuerySettings(optimize_aggregation_in_order=True)-- persons_query, query_params = await compile_hogql_for_streaming(persons_query_ast, team_id=inputs.team_id)-- last_person_id = inputs.start_person_id- batch_count = 0-- logger.info("Starting ClickHouse client connection and query execution")-- with tags_context(- team_id=inputs.team_id,- feature=Feature.BEHAVIORAL_COHORTS,- product=Product.MESSAGING,- query_type="person_properties_backfill",- ):- logger.info("Acquiring ClickHouse client connection", team_id=inputs.team_id)- async with get_messaging_client(team_id=inputs.team_id) as client:- logger.info(- "ClickHouse client connection established, starting query execution",- team_id=inputs.team_id,- query=persons_query,- query_params=query_params,- )- # Time the ClickHouse query execution- query_start_time = time.monotonic()-- first_row = True- async for row in client.stream_query_as_jsonl(persons_query, query_parameters=query_params):- if first_row:- query_first_row_time = time.monotonic()- logger.info(- "First row received from ClickHouse query",- team_id=inputs.team_id,- time_to_first_row_seconds=round(query_first_row_time - query_start_time, 2),- first_person_id=str(row["id"]),- )- first_row = False- batch_count += 1- person_id = str(row["id"])- last_person_id = person_id # Track the last person ID for next cursor-- # Handle both optimized (individual property columns) and fallback (full properties JSON) formats- if person_properties and FULL_PROPERTIES_KEY not in row:- # Optimized format: reconstruct properties dict from individual columns using alias mapping- reconstructed_properties = {}- for alias, original_prop_name in property_alias_mapping.items():- value = row.get(alias)- # The HogQL property extract maps a missing key to SQL NULL (-> None here),- # while a present falsey value (0, false, "") comes back as a non-null string.- # Keying on ``is not None`` keeps those present-but-falsey values instead of- # silently turning them into a missing key, matching the full-properties fallback.- if value is not None:- reconstructed_properties[original_prop_name] = value-- parsed_properties = parse_person_properties(reconstructed_properties, person_id)- else:- # Fallback format: use full properties JSON- parsed_properties = parse_person_properties(row.get(FULL_PROPERTIES_KEY), person_id)-- # Evaluate all filters in a single VM call- person_filter_start = time.monotonic()- hog_globals = {"person": {"properties": parsed_properties}}-- filter_results = await asyncio.to_thread(- evaluate_combined_filters_with_fallback_sync,- combined_bytecode,- filters,- hog_globals,- person_id,- detailed_logging=detailed_logging_enabled,- )-- # Detailed logging for filter results when in single cohort + single person mode- if detailed_logging_enabled:- person_filter_duration = time.monotonic() - person_filter_start- matching_conditions = [- condition_hash for condition_hash, matches in filter_results.items() if matches- ]- logger.info(- "Filter evaluation results",- person_id=person_id,- total_conditions=len(filter_results),- matching_conditions=len(matching_conditions),- matching_condition_hashes=matching_conditions,- all_results=filter_results,- evaluation_duration_ms=round(person_filter_duration * 1000, 2),- person_properties_count=len(parsed_properties),- )-- # Produce Kafka messages for matching conditions- for condition_hash, matches in filter_results.items():- if matches:- try:- produce_result = kafka_producer.produce(- topic=KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,- data={- "team_id": inputs.team_id,- "distinct_id": person_id,- "person_id": person_id,- "condition": condition_hash,- "matches": matches,- "source": f"cohort_filter_{condition_hash}",- },- )- kafka_results.append(produce_result)- total_events_produced += 1-- if detailed_logging_enabled:- logger.info(- "Kafka message produced for matching condition",- person_id=person_id,- condition_hash=condition_hash,- matches=matches,- kafka_topic=KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,- )- except Exception as e:- logger.warning(- f"Failed to produce Kafka message for person {person_id}: {e}",- person_id=person_id,- condition_hash=condition_hash,- error=str(e),- )-- # Periodically flush Kafka batches to avoid memory buildup- if len(kafka_results) >= KAFKA_FLUSH_BATCH_SIZE:- logger.info(- f"Flushing {len(kafka_results)} Kafka messages (batch size: {KAFKA_FLUSH_BATCH_SIZE})"- )- batch_flushed = await flush_kafka_batch_async(- kafka_results,- kafka_producer,- inputs.team_id,- logger,- )- total_flushed += batch_flushed- kafka_results.clear() # Clear the batch after flushing-- # Record filter evaluation timing for this person- person_filter_duration = time.monotonic() - person_filter_start- if filter_evaluation_duration_metric:- filter_evaluation_duration_metric.record(- person_filter_duration, {"team_id": str(inputs.team_id), "filter_count": str(len(filters))}- )-- # Record query timing and person processing rate- query_duration = time.monotonic() - query_start_time- if query_duration_metric and batch_count > 0:- query_duration_metric.record(query_duration, {"team_id": str(inputs.team_id)})-- if person_processing_rate_metric and query_duration > 0:- processing_rate = batch_count / query_duration- person_processing_rate_metric.record(processing_rate, {"team_id": str(inputs.team_id)})-- logger.info(- f"Processed {batch_count} persons from {inputs.start_person_id} to {last_person_id} (range: {inputs.start_person_id} - {inputs.end_person_id})"- )- total_processed = batch_count-- # Update heartbeat- heartbeater.details = (- f"Processed {total_processed} persons, produced {total_events_produced} events, pending {len(kafka_results)} messages",- )-- # Flush all collected Kafka results- if kafka_results:- logger.info(f"Final flush of {len(kafka_results)} Kafka results", team_id=inputs.team_id)- final_flushed = await flush_kafka_batch_async(- kafka_results,- kafka_producer,- inputs.team_id,- logger,- )- total_flushed += final_flushed-- end_time = time.time()- duration_seconds = end_time - start_time-- get_person_properties_backfill_success_metric().add(1)-- logger.info(- f"Completed person properties precalculation: processed {total_processed} persons, "- f"produced {total_events_produced} events, flushed {total_flushed} in {duration_seconds:.1f} seconds",- persons_processed=total_processed,- events_produced=total_events_produced,- events_flushed=total_flushed,- duration_seconds=duration_seconds,- )-- return BackfillPrecalculatedPersonPropertiesResult(- persons_processed=total_processed,- events_produced=total_events_produced,- events_flushed=total_flushed,- last_person_id=last_person_id if batch_count > 0 else None,- duration_seconds=duration_seconds,- )--[email protected](name="backfill-precalculated-person-properties")-class BackfillPrecalculatedPersonPropertiesWorkflow(PostHogWorkflow):- """Workflow that backfills precalculated person properties for a team's cohorts."""-- @staticmethod- def parse_inputs(inputs: list[str]) -> BackfillPrecalculatedPersonPropertiesInputs:- """Parse inputs from the management command CLI."""- # This would be called programmatically, not from CLI- raise NotImplementedError("Use start_workflow() to trigger this workflow programmatically")-- @temporalio.workflow.run- async def run(- self, inputs: BackfillPrecalculatedPersonPropertiesInputs- ) -> BackfillPrecalculatedPersonPropertiesResult:- """Run the workflow to backfill precalculated person properties for a specific ID range."""- workflow_logger = temporalio.workflow.logger- cohort_ids = inputs.cohort_ids- workflow_logger.info(- f"Starting person properties precalculation for {len(cohort_ids)} cohorts {format_cohort_ids_for_logging(cohort_ids)} "- f"(team {inputs.team_id}, range: {inputs.start_person_id} - {inputs.end_person_id})"- )-- # Process the specific ID range- result = await temporalio.workflow.execute_activity(- backfill_precalculated_person_properties_activity,- inputs,- start_to_close_timeout=dt.timedelta(hours=12), # Long timeout for large batches- heartbeat_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=3,- initial_interval=dt.timedelta(seconds=10),- maximum_interval=dt.timedelta(minutes=1),- ),- )-- workflow_logger.info(- f"Completed person properties precalculation: processed {result.persons_processed} persons, "- f"produced {result.events_produced} events, flushed {result.events_flushed} events "- f"(range: {inputs.start_person_id} - {inputs.end_person_id})"- )-- return resultdiff --git a/posthog/temporal/messaging/clickhouse_concurrency.py b/posthog/temporal/messaging/clickhouse_concurrency.pydeleted file mode 100644index d03c126c9a1d..000000000000--- a/posthog/temporal/messaging/clickhouse_concurrency.py+++ /dev/null@@ -1,35 +0,0 @@-import asyncio-from collections.abc import AsyncIterator-from contextlib import asynccontextmanager--from django.conf import settings--from posthog.temporal.common.clickhouse import ClickHouseClient, get_client--# Limits concurrent offline-cluster ClickHouse queries across the messaging workflow family-# (reconcile-precalculated-data, realtime-cohort-calculation, and the precalculated backfills).-# They all run on one worker process with a single event loop, so this module-level semaphore-# gates every messaging activity on the same worker. Acquiring a slot before opening-# `get_client()` turns an over-cap situation into in-process backpressure (waiting) instead of a-# ClickHouse TOO_MANY_SIMULTANEOUS_QUERIES rejection. The cap is per worker process; aggregate =-# this value times messaging worker replicas.-#-# This does not coordinate with other offline consumers: data_modeling runs its own independent-# semaphore against the same offline `default` user, on a separate task queue / worker / event-# loop (see data_modeling/activities/materialize_view.py). The real cluster-wide budget is the-# sum across all such families, so keep this value low enough to leave them headroom under 30.-#-# Floored at 1: a size of 0 (misconfigured env) would deadlock every gated activity forever, since-# no permit is ever released.-messaging_clickhouse_query_semaphore = asyncio.Semaphore(max(1, settings.MESSAGING_CLICKHOUSE_MAX_CONCURRENT_QUERIES))---@asynccontextmanager-async def get_messaging_client(team_id: int) -> AsyncIterator[ClickHouseClient]:- """Open a ClickHouse client while holding a messaging query slot.-- Every messaging offline-cluster query must go through here so the per-worker concurrency cap- can't be defeated by a call site that forgets to acquire the semaphore first.- """- async with messaging_clickhouse_query_semaphore, get_client(team_id=team_id) as client:- yield clientdiff --git a/posthog/temporal/messaging/constants.py b/posthog/temporal/messaging/constants.pydeleted file mode 100644index cefc38d9c13c..000000000000--- a/posthog/temporal/messaging/constants.py+++ /dev/null@@ -1,25 +0,0 @@-"""Shared constants for temporal messaging workflows."""--# precalculated_events.source prefix written by the event backfill (as opposed to the-# realtime consumer, which writes a "cohort_filter_" prefix). Shared so the day-already--# backfilled check and the backfill writer can't drift apart.-BACKFILL_EVENT_SOURCE_PREFIX = "cohort_event_backfill"--CHILD_WORKFLOW_ID_SUFFIX = "child"---def get_child_workflow_id(parent_workflow_id: str, child_index: int) -> str:- """Generate a standardized child workflow ID."""- return f"{parent_workflow_id}-{CHILD_WORKFLOW_ID_SUFFIX}-{child_index}"---def get_percentile_bucket_label(min_percentile: float | None, max_percentile: float | None) -> str:- """Generate percentile bucket label for metrics from min/max percentile values."""- if min_percentile is None and max_percentile is None:- return "manual"- elif min_percentile is None:- return f"p0-p{int(max_percentile) if max_percentile is not None else 0}"- elif max_percentile is None:- return f"p{int(min_percentile) if min_percentile is not None else 0}-p100"- else:- return f"p{int(min_percentile)}-p{int(max_percentile)}"diff --git a/posthog/temporal/messaging/filter_storage.py b/posthog/temporal/messaging/filter_storage.pydeleted file mode 100644index b5610a9cb8b7..000000000000--- a/posthog/temporal/messaging/filter_storage.py+++ /dev/null@@ -1,311 +0,0 @@-"""-Redis-based filter storage service for managing large filter datasets in backfill workflows.--This module provides temporary storage for PersonPropertyFilter collections to avoid Temporal-blob size limits when passing large filter payloads between workflows and activities.--TTL Considerations:-- Individual activities have start_to_close_timeout=12h with maximum_attempts=3-- Coordinator workflows spawn multiple child workflows with batch delays-- Total workflow execution time in worst case: 3 retries × 12h + batch delays ≈ 40-48h-- TTL set to 168h (7 days) provides generous safety margin for retries and delays-- If workflows consistently approach TTL (7d), consider TTL refresh logic in get_filters()-"""--import json-import hashlib-from typing import Any--import structlog--from posthog.redis import get_client-from posthog.temporal.messaging.types import BehavioralEventFilter, PersonPropertyFilter--from products.cohorts.backend.models.cohort import Cohort--from common.hogvm.python.operation import HOGQL_BYTECODE_IDENTIFIER, Operation--KEY_PREFIX = "backfill_person_properties_filters:"-EVENT_KEY_PREFIX = "backfill_event_filters:"-# TTL sizing: Worst case workflow duration ~48h (3 × 12h retries + batch delays)-# 168h provides generous safety margin for complex backfill operations that may run longer.-DEFAULT_TTL = 168 * 60 * 60 # 7 days--logger = structlog.get_logger(__name__)---def combine_filter_bytecodes(filters: list[PersonPropertyFilter]) -> list[Any]:- """Combine multiple filter bytecodes into a single bytecode returning a dict.-- Strips the header from each filter's bytecode body, interleaves condition_hash- keys, and appends a DICT opcode to collect all results into- {condition_hash: bool_result, ...}.-- Built once at coordinator startup and reused for every person.- """- combined: list[Any] = [HOGQL_BYTECODE_IDENTIFIER, 1]-- valid_count = 0- for f in filters:- if len(f.bytecode) <= 2:- logger.warning(- "Skipping malformed bytecode for filter",- condition_hash=f.condition_hash,- bytecode_length=len(f.bytecode),- )- continue- combined.append(Operation.STRING)- combined.append(f.condition_hash)- combined.extend(f.bytecode[2:])- valid_count += 1-- combined.append(Operation.DICT)- combined.append(valid_count)-- 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.-- Args:- filters: List of PersonPropertyFilter objects to store- team_id: Team ID for namespacing- ttl: Time to live in seconds-- Returns:- Storage key that can be used to retrieve the filters- """- # Create serializable filter data- filter_data = [- {- "condition_hash": f.condition_hash,- "bytecode": f.bytecode,- "cohort_ids": f.cohort_ids,- "property_key": f.property_key,- }- for f in filters- ]-- # Extract person properties from filters using the property_key field- person_properties = set()- for f in filters:- if f.property_key:- person_properties.add(f.property_key)-- # Combine all filter bytecodes into a single optimized bytecode- combined_bytecode = combine_filter_bytecodes(filters)-- # Create storage object containing filters, properties, and combined bytecode- storage_data = {- "filters": filter_data,- "person_properties": sorted(person_properties), # Sort for consistent ordering- "combined_bytecode": combined_bytecode,- }-- # Create hash of the storage data for the key- content_hash = hashlib.sha256(json.dumps(storage_data, sort_keys=True).encode()).hexdigest()-- storage_key = f"{KEY_PREFIX}team_{team_id}_{content_hash}"-- # Store the serialized data in Redis- get_client().setex(storage_key, ttl, json.dumps(storage_data))-- return storage_key---def get_filters_and_properties(storage_key: str) -> tuple[list[PersonPropertyFilter], list[str], list[Any]] | None:- """- Retrieve filters, person properties, and combined bytecode using a storage key.-- Args:- storage_key: Key returned by store_filters-- Returns:- Tuple of (filters, person_properties, combined_bytecode), or None if not found-- Note:- If workflows consistently approach TTL (7d) and expiration becomes an issue,- consider adding TTL refresh logic here using Redis EXPIRE command.- """- data = get_client().get(storage_key)- if data is None:- return None-- storage_data = json.loads(data.decode("utf-8"))- filter_data = storage_data["filters"]- person_properties = storage_data["person_properties"]- combined_bytecode = storage_data.get("combined_bytecode")-- # Reconstruct PersonPropertyFilter objects- filters = [- PersonPropertyFilter(- condition_hash=item["condition_hash"],- bytecode=item["bytecode"],- cohort_ids=item["cohort_ids"],- property_key=item["property_key"],- )- for item in filter_data- ]-- # If combined_bytecode is not present (backward compatibility), generate it- if combined_bytecode is None:- combined_bytecode = combine_filter_bytecodes(filters)-- return filters, person_properties, combined_bytecode---def combine_event_filter_bytecodes(filters: list[BehavioralEventFilter]) -> list[Any]:- """Combine multiple behavioral event filter bytecodes into a single bytecode returning a dict.-- Same strategy as combine_filter_bytecodes: strips headers, interleaves condition_hash keys,- and appends a DICT opcode. The resulting bytecode returns {condition_hash: bool_result, ...}- when executed with event globals.-- Malformed filters (bytecode length <= 2) are silently skipped with a warning log. If all- filters are malformed, the result is a valid bytecode that produces an empty dict.- """- combined: list[Any] = [HOGQL_BYTECODE_IDENTIFIER, 1]-- valid_count = 0- for f in filters:- if len(f.bytecode) <= 2:- logger.warning(- "Skipping malformed bytecode for event filter",- condition_hash=f.condition_hash,- event_name=f.event_name,- bytecode_length=len(f.bytecode),- )- continue- combined.append(Operation.STRING)- combined.append(f.condition_hash)- combined.extend(f.bytecode[2:])- valid_count += 1-- combined.append(Operation.DICT)- combined.append(valid_count)-- return combined---def store_event_filters(filters: list[BehavioralEventFilter], team_id: int, ttl: int = DEFAULT_TTL) -> str:- """Store behavioral event filters in Redis and return a storage key.-- Filters are grouped by event name and a combined bytecode is built per group,- enabling efficient per-event-name evaluation during the backfill scan.- """- filter_data = [- {- "condition_hash": f.condition_hash,- "bytecode": f.bytecode,- "cohort_ids": f.cohort_ids,- "event_name": f.event_name,- "time_value": f.time_value,- "time_interval": f.time_interval,- "event_filters": f.event_filters,- }- for f in filters- ]-- # Group filters by event name for per-event combined bytecodes- event_name_groups: dict[str, list[BehavioralEventFilter]] = {}- for f in filters:- event_name_groups.setdefault(f.event_name, []).append(f)-- combined_bytecodes_by_event: dict[str, list[Any]] = {- event_name: combine_event_filter_bytecodes(group) for event_name, group in sorted(event_name_groups.items())- }-- storage_data = {- "filters": filter_data,- "event_names": sorted(event_name_groups.keys()),- "combined_bytecodes_by_event": combined_bytecodes_by_event,- }-- content_hash = hashlib.sha256(json.dumps(storage_data, sort_keys=True).encode()).hexdigest()- storage_key = f"{EVENT_KEY_PREFIX}team_{team_id}_{content_hash}"-- get_client().setex(storage_key, ttl, json.dumps(storage_data))-- return storage_key---def get_event_filters(- storage_key: str,-) -> tuple[list[BehavioralEventFilter], list[str], dict[str, list[Any]]] | None:- """Retrieve behavioral event filters, event names, and per-event combined bytecodes.-- Returns:- Tuple of (filters, event_names, combined_bytecodes_by_event), or None if not found.- """- data = get_client().get(storage_key)- if data is None:- return None-- storage_data = json.loads(data.decode("utf-8"))- filter_data = storage_data["filters"]- event_names = storage_data["event_names"]- combined_bytecodes_by_event = storage_data.get("combined_bytecodes_by_event", {})-- filters = [- BehavioralEventFilter(- condition_hash=item["condition_hash"],- bytecode=item["bytecode"],- cohort_ids=item["cohort_ids"],- event_name=item["event_name"],- time_value=item["time_value"],- time_interval=item["time_interval"],- event_filters=item.get("event_filters"),- )- for item in filter_data- ]-- # Regenerate combined bytecodes if missing (backward compatibility)- if not combined_bytecodes_by_event:- event_name_groups: dict[str, list[BehavioralEventFilter]] = {}- for f in filters:- event_name_groups.setdefault(f.event_name, []).append(f)- combined_bytecodes_by_event = {- event_name: combine_event_filter_bytecodes(group) for event_name, group in sorted(event_name_groups.items())- }-- return filters, event_names, combined_bytecodes_by_eventdiff --git a/posthog/temporal/messaging/hogql_compile.py b/posthog/temporal/messaging/hogql_compile.pydeleted file mode 100644index 40e54b1dbeed..000000000000--- a/posthog/temporal/messaging/hogql_compile.py+++ /dev/null@@ -1,33 +0,0 @@-from typing import Any--from posthog.hogql import ast-from posthog.hogql.constants import LimitContext-from posthog.hogql.context import HogQLContext-from posthog.hogql.printer import prepare_and_print_ast--from posthog.sync import database_sync_to_async_pool---@database_sync_to_async_pool-def compile_hogql_for_streaming(node: ast.SelectQuery, *, team_id: int) -> tuple[str, dict[str, Any]]:- """Compile a HogQL ``SelectQuery`` to ClickHouse SQL for the streaming HTTP client.-- Backfill workflows in this package run HogQL on a background path that has no- request-scoped user. They need the activity to behave identically to the previous- raw-SQL implementation, so property access-control restrictions are explicitly- bypassed with ``restricted_properties=set()`` — otherwise the printer would call- ``get_restricted_properties_for_team(team_id, user=None)``, which applies any- property-level rules and would silently change cohort evaluation results compared- to the raw-SQL baseline.-- Returns the printed SQL and the parameter dict captured on the printer context.- """- hogql_context = HogQLContext(- team_id=team_id,- enable_select_queries=True,- limit_context=LimitContext.COHORT_CALCULATION,- output_format="JSONEachRow",- restricted_properties=set(),- )- sql, _ = prepare_and_print_ast(node, hogql_context, "clickhouse")- return sql, hogql_context.valuesdiff --git a/posthog/temporal/messaging/quantiles_storage.py b/posthog/temporal/messaging/quantiles_storage.pydeleted file mode 100644index f99f71011d85..000000000000--- a/posthog/temporal/messaging/quantiles_storage.py+++ /dev/null@@ -1,364 +0,0 @@-"""-Redis-based quantiles storage service for consistent percentile thresholds across workflows.--This module provides atomic caching of duration quantiles to ensure all realtime cohort workflows-use the same percentile boundaries, preventing overlapping threshold ranges between tiers.--Race Condition Handling:-- Uses Redis SET NX (atomic set-if-not-exists) to prevent multiple workflows from calculating quantiles-- Implements retry logic with exponential backoff when cache write fails due to race conditions-- TTL set to 2 hours to ensure fresh data while allowing workflow coordination-"""--import json-import time-import uuid-import random-import datetime as dt-import statistics-import dataclasses-from typing import Optional--import structlog--from posthog.redis import get_client--LOGGER = structlog.get_logger(__name__)--# Cache key format: quantiles:2024-01-15:14 (hourly buckets)-QUANTILES_KEY_PREFIX = "duration_quantiles:"-# Short TTL since we want relatively fresh data but need consistency within the hour-DEFAULT_TTL = 2 * 60 * 60 # 2 hours-# Lock to prevent race conditions when calculating quantiles-LOCK_KEY_PREFIX = "duration_quantiles_lock:"-LOCK_TTL = 300 # 5 minutes-# Retry configuration for handling race conditions-# Conservative limits to avoid blocking database_sync_to_async thread pool-MAX_RETRIES = 3-BASE_RETRY_DELAY = 0.05 # 50ms-MAX_RETRY_DELAY = 0.2 # 200ms max--[email protected](frozen=True)-class CachedQuantiles:- """Cached quantile boundaries plus the maximum observed value used for p100.-- Caching the max alongside the quantiles guarantees workflows that share the same- cache entry produce identical p100 thresholds, even if the underlying queryset- changes between workflows within the cache window.- """-- quantiles: list[float]- max_value: int---def _get_cache_key(hour_bucket: str) -> str:- """Generate Redis key for quantiles cache."""- return f"{QUANTILES_KEY_PREFIX}{hour_bucket}"---def _get_lock_key(hour_bucket: str) -> str:- """Generate Redis key for quantiles calculation lock."""- return f"{LOCK_KEY_PREFIX}{hour_bucket}"---def _get_current_hour_bucket() -> str:- """Get current hour bucket for cache key (e.g., '2024-01-15:14')."""- now = dt.datetime.now(dt.UTC)- return now.strftime("%Y-%m-%d:%H")---def _get_previous_hour_bucket() -> str:- """Get previous hour bucket for fallback cache lookup (e.g., '2024-01-15:13')."""- now = dt.datetime.now(dt.UTC)- previous_hour = now - dt.timedelta(hours=1)- return previous_hour.strftime("%Y-%m-%d:%H")---def store_quantiles(quantiles_data: list[float], max_value: int, hour_bucket: Optional[str] = None) -> bool:- """- Atomically store quantiles in Redis if not already cached.-- Args:- quantiles_data: List of 99 quantile values (p1 through p99)- max_value: Maximum observed duration; used as the p100 threshold by all- workflows that share this cache entry, ensuring tier consistency.- hour_bucket: Optional hour bucket, defaults to current hour-- Returns:- True if successfully stored, False if another process already stored them- """- if hour_bucket is None:- hour_bucket = _get_current_hour_bucket()-- cache_key = _get_cache_key(hour_bucket)- lock_key = _get_lock_key(hour_bucket)-- redis_client = get_client()- lock_token = None-- try:- # Generate unique token for this lock acquisition- lock_token = uuid.uuid4().hex-- # Try to acquire lock atomically with unique token- lock_acquired = redis_client.set(lock_key, lock_token, nx=True, ex=LOCK_TTL) or False-- if not lock_acquired:- LOGGER.info(- "Quantiles calculation lock already held by another process",- hour_bucket=hour_bucket,- cache_key=cache_key,- )- return False-- # Check if cache was set while we were acquiring the lock- if redis_client.exists(cache_key):- LOGGER.info(- "Quantiles already cached by another process during lock acquisition",- hour_bucket=hour_bucket,- cache_key=cache_key,- )- return False-- # Store quantiles with TTL- payload_json = json.dumps({"quantiles": quantiles_data, "max_value": max_value})- redis_client.setex(cache_key, DEFAULT_TTL, payload_json)-- LOGGER.info(- "Successfully stored quantiles in cache",- hour_bucket=hour_bucket,- cache_key=cache_key,- quantiles_count=len(quantiles_data),- max_value=max_value,- ttl_seconds=DEFAULT_TTL,- )-- return True-- except Exception as e:- LOGGER.warning("Failed to store quantiles in cache", hour_bucket=hour_bucket, cache_key=cache_key, error=str(e))- return False-- finally:- # Only release the lock if we acquired it and still hold the same token- if lock_token:- try:- # Use Lua script for atomic compare-and-delete- lua_script = """- if redis.call("GET", KEYS[1]) == ARGV[1] then- return redis.call("DEL", KEYS[1])- else- return 0- end- """- result = redis_client.eval(lua_script, 1, lock_key, lock_token)- if result == 0:- LOGGER.warning(- "Lock token mismatch during release - lock may have expired or been taken by another process",- lock_key=lock_key,- hour_bucket=hour_bucket,- )- except Exception as e:- LOGGER.warning("Failed to release quantiles calculation lock", lock_key=lock_key, error=str(e))---def get_quantiles(hour_bucket: Optional[str] = None) -> Optional[CachedQuantiles]:- """- Retrieve cached quantiles from Redis.-- Args:- hour_bucket: Optional hour bucket, defaults to current hour-- Returns:- CachedQuantiles with 99 quantile values and the cached max if cached,- None if not found or unparseable.- """- if hour_bucket is None:- hour_bucket = _get_current_hour_bucket()-- cache_key = _get_cache_key(hour_bucket)- redis_client = get_client()-- try:- cached_data = redis_client.get(cache_key)-- if cached_data is None:- LOGGER.info("No quantiles found in cache", hour_bucket=hour_bucket, cache_key=cache_key)- return None-- payload = json.loads(cached_data)-- # Reject any payload that doesn't carry both quantiles and max_value, including- # legacy bare-list entries from earlier versions of this branch. Treat as a miss- # so callers fall back to recalculation rather than silently mixing formats.- if not isinstance(payload, dict) or "quantiles" not in payload or "max_value" not in payload:- LOGGER.warning(- "Cached quantiles payload is missing required fields",- hour_bucket=hour_bucket,- cache_key=cache_key,- )- try:- redis_client.delete(cache_key)- except Exception:- pass- return None-- cached = CachedQuantiles(quantiles=payload["quantiles"], max_value=int(payload["max_value"]))-- LOGGER.info(- "Successfully retrieved quantiles from cache",- hour_bucket=hour_bucket,- cache_key=cache_key,- quantiles_count=len(cached.quantiles),- max_value=cached.max_value,- )-- return cached-- except (json.JSONDecodeError, TypeError, ValueError) as e:- LOGGER.warning(- "Failed to parse cached quantiles data", hour_bucket=hour_bucket, cache_key=cache_key, error=str(e)- )- # Delete corrupted cache entry- try:- redis_client.delete(cache_key)- except Exception:- pass- return None-- except Exception as e:- LOGGER.warning(- "Failed to retrieve quantiles from cache", hour_bucket=hour_bucket, cache_key=cache_key, error=str(e)- )- return None---def get_cached_quantiles_or_calculate(- durations_list: list[int], hour_bucket: Optional[str] = None, max_retries: int = MAX_RETRIES-) -> Optional[CachedQuantiles]:- """- Get quantiles from cache first, regardless of current data size.- Only calculate new quantiles if cache is empty and we have sufficient data.-- This ensures workflows can reuse cached quantiles even when the current- query returns insufficient data (e.g., cohort count dropped mid-hour).- """- if hour_bucket is None:- hour_bucket = _get_current_hour_bucket()-- # First, try to get from current hour bucket cache- cached = get_quantiles(hour_bucket)- if cached is not None:- return cached-- # Cache miss - try previous hour bucket to handle hour-boundary issue- # This prevents overlapping thresholds when schedules run near :59/:00- previous_hour_bucket = _get_previous_hour_bucket()- if previous_hour_bucket != hour_bucket: # Only check if different from current- cached = get_quantiles(previous_hour_bucket)- if cached is not None:- LOGGER.info(- "Using quantiles from previous hour bucket to handle hour-boundary timing",- current_bucket=hour_bucket,- previous_bucket=previous_hour_bucket,- )- return cached-- # No cache available - only calculate if we have sufficient current data- if len(durations_list) < 2:- LOGGER.error(- "No cached quantiles available and insufficient current data for calculation",- hour_bucket=hour_bucket,- previous_bucket=previous_hour_bucket,- data_points=len(durations_list),- )- return None-- # Continue with calculation using the current implementation- return _calculate_and_cache_quantiles(durations_list, hour_bucket, max_retries)---def _calculate_and_cache_quantiles(- durations_list: list[int], hour_bucket: str, max_retries: int = MAX_RETRIES-) -> Optional[CachedQuantiles]:- """- Calculate and cache quantiles atomically with retry logic for race conditions.-- Assumes cache has already been checked. This function only calculates new quantiles- when we know we have sufficient data and need to populate the cache.-- Args:- durations_list: List of duration values in milliseconds (must have >= 2 elements)- hour_bucket: Time bucket for cache key- max_retries: Maximum number of retries for handling race conditions-- Returns:- CachedQuantiles with 99 quantile values (p1 through p99) and the max- observed duration, or None on failure.- """- try:- # Calculate quantiles and capture max from the same dataset so the cached- # p100 stays in lockstep with the cached p1..p99 boundaries.- quantiles = statistics.quantiles(durations_list, n=100, method="inclusive")- max_value = int(max(durations_list))-- # Try to store in cache with retry logic for race conditions- for attempt in range(max_retries):- stored = store_quantiles(quantiles, max_value, hour_bucket)-- if stored:- # We successfully stored the quantiles- LOGGER.info(- "Successfully calculated and cached quantiles",- hour_bucket=hour_bucket,- attempt=attempt + 1,- data_points=len(durations_list),- )- return CachedQuantiles(quantiles=quantiles, max_value=max_value)-- # Another process stored quantiles while we were calculating- # Try to retrieve the stored values- cached = get_quantiles(hour_bucket)- if cached is not None:- LOGGER.info(- "Using quantiles calculated by another process", hour_bucket=hour_bucket, attempt=attempt + 1- )- return cached-- # Cache still empty, retry with exponential backoff- if attempt < max_retries - 1:- delay = min(BASE_RETRY_DELAY * (2**attempt) + random.uniform(0, 0.1), MAX_RETRY_DELAY)- LOGGER.info(- "Retrying quantiles calculation after delay",- hour_bucket=hour_bucket,- attempt=attempt + 1,- delay_seconds=delay,- )- time.sleep(delay)-- # All retries exhausted. Do not return uncached locally computed quantiles,- # because doing so can reintroduce inconsistent percentile boundaries across workflows.- # Perform one final cache read in case another process populated the cache- # after our last retry attempt, otherwise fail closed.- cached = get_quantiles(hour_bucket)- if cached is not None:- LOGGER.info(- "Using quantiles calculated by another process after final cache check",- hour_bucket=hour_bucket,- max_retries=max_retries,- )- return cached-- LOGGER.error(- "Failed to obtain cached quantiles after all retries; returning None to preserve consistency",- hour_bucket=hour_bucket,- max_retries=max_retries,- )- return None-- except (statistics.StatisticsError, TypeError, ValueError) as e:- LOGGER.warning(- "Failed to calculate quantiles", hour_bucket=hour_bucket, error=str(e), data_points=len(durations_list)- )- return Nonediff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.pydeleted file mode 100644index 3daf6cc855a2..000000000000--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py+++ /dev/null@@ -1,665 +0,0 @@-import os-import time-import asyncio-import datetime as dt-import dataclasses-from typing import TYPE_CHECKING, Any, Optional--from django.utils import timezone--import temporalio.activity-import temporalio.workflow-from prometheus_client import Histogram-from structlog.contextvars import bind_contextvars--from posthog.hogql.constants import LimitContext-from posthog.hogql.context import HogQLContext-from posthog.hogql.printer import prepare_and_print_ast--from posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.hogql_queries.hogql_cohort_query import HogQLRealtimeCohortQuery-from posthog.kafka_client.routing import get_producer-from posthog.kafka_client.topics import KAFKA_COHORT_MEMBERSHIP_CHANGED-from posthog.sync import database_sync_to_async-from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.heartbeat import Heartbeater-from posthog.temporal.common.logger import get_logger-from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_client-from posthog.temporal.messaging.constants import get_percentile_bucket_label--from products.cohorts.backend.models.cohort import Cohort, CohortType--if TYPE_CHECKING:- from posthog.kafka_client.client import _KafkaProducer--# Configuration-FLUSH_BATCH_SIZE = int(os.environ.get("COHORT_KAFKA_FLUSH_BATCH_SIZE", "1000"))-DURATION_UPDATE_RELATIVE_THRESHOLD = 0.25 # Only update duration when change exceeds 25%-# Spill the cohort-membership GROUP BY to disk once it exceeds this fraction of the query's-# memory limit, instead of OOMing. See build_final_query.-EXTERNAL_GROUP_BY_MEMORY_RATIO = 0.5--# Cohort calculation timing histograms-COHORT_CALCULATION_TOTAL_DURATION_HISTOGRAM = Histogram(- "cohort_calculation_total_duration_seconds",- "Total duration of cohort calculation from start to finish",- ["percentile_bucket"],- buckets=(0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, float("inf")),-)--COHORT_QUERY_EXECUTION_DURATION_HISTOGRAM = Histogram(- "cohort_query_execution_duration_seconds",- "Duration of ClickHouse query execution for cohort calculation",- ["percentile_bucket"],- buckets=(0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, float("inf")),-)--COHORT_DURATION_UPDATE_HISTOGRAM = Histogram(- "cohort_duration_update_seconds",- "Duration of updating cohort duration in database",- ["percentile_bucket"],- buckets=(0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, float("inf")),-)--# Kafka operation metrics-KAFKA_PRODUCE_DURATION_HISTOGRAM = Histogram(- "cohort_kafka_produce_duration_seconds",- "Time spent producing individual messages to Kafka",- ["percentile_bucket"],- buckets=(0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, float("inf")),-)--KAFKA_FLUSH_DURATION_HISTOGRAM = Histogram(- "cohort_kafka_flush_duration_seconds",- "Time spent flushing Kafka message batches",- ["percentile_bucket"],- buckets=(0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, float("inf")),-)--# Query building metrics-QUERY_BUILD_DURATION_HISTOGRAM = Histogram(- "cohort_query_build_duration_seconds",- "Time spent building HogQL queries for cohort calculation",- ["percentile_bucket"],- buckets=(0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, float("inf")),-)--# Row processing metrics-ROW_PROCESSING_RATE_HISTOGRAM = Histogram(- "cohort_rows_processed_per_second",- "Rate of processing rows from ClickHouse query results",- ["percentile_bucket"],- buckets=(1, 10, 50, 100, 500, 1000, 5000, 10000, 50000, float("inf")),-)--# Child workflow total duration metrics-CHILD_WORKFLOW_TOTAL_DURATION_HISTOGRAM = Histogram(- "realtime_cohort_child_total_duration_seconds",- "Total duration of child workflow activity execution in seconds",- ["percentile_bucket"],- buckets=(1, 10, 30, 60, 120, 300, 600, 1800, 3600, float("inf")),-)--LOGGER = get_logger(__name__)--# Sampling rate for Kafka produce duration metrics to reduce overhead-KAFKA_PRODUCE_METRIC_SAMPLE_RATE = 1000---def get_cohort_calculation_success_metric():- """Counter for successful cohort calculations."""- return temporalio.activity.metric_meter().create_counter(- "realtime_cohort_calculation_success", "Number of successful realtime cohort calculations"- )---def get_cohort_calculation_failure_metric():- """Counter for failed cohort calculations."""- return temporalio.activity.metric_meter().create_counter(- "realtime_cohort_calculation_failure", "Number of failed realtime cohort calculations"- )---def get_membership_changed_metric(status: str, percentile_bucket: str):- """Counter for cohort membership changes by status (entered/left) and percentile bucket."""- return (- temporalio.activity.metric_meter()- .with_additional_attributes({"status": status, "percentile_bucket": percentile_bucket})- .create_counter(- "realtime_cohort_membership_changed",- "Number of cohort membership changes (people entering or leaving cohorts)",- )- )---class RealtimeCohortCalculationWorkflowInputs:- """Inputs for the realtime cohort calculation workflow."""-- # Array-based approach: coordinator provides specific cohort IDs to process- cohort_ids: Optional[list[int]] = None-- # Keep cohort_id for backward compatibility with single cohort processing- cohort_id: Optional[int] = None-- # Percentile bucket information for metrics- duration_percentile_min: Optional[float] = None- duration_percentile_max: Optional[float] = None-- @property- def properties_to_log(self) -> dict[str, Any]:- if self.cohort_id is not None:- return {- "cohort_id": self.cohort_id,- "num_cohorts": 1,- }- elif self.cohort_ids is not None:- return {- "cohort_ids": self.cohort_ids[:10]- if len(self.cohort_ids) > 10- else self.cohort_ids, # Log first 10 for brevity- "num_cohorts": len(self.cohort_ids),- }- else:- return {- "num_cohorts": 0,- }---async def flush_kafka_batch(- kafka_producer: "_KafkaProducer",- pending_messages: list,- cohort_id: int,- idx: int,- total_cohorts: int,- heartbeater,- logger,- percentile_bucket: str,- is_final: bool = False,-) -> int:- """Flush a batch of Kafka messages and check for failures.-- Returns the number of messages flushed.- """- if not pending_messages:- return 0-- batch_size = len(pending_messages)- batch_type = "final " if is_final else ""- heartbeater.details = (- f"Flushing {batch_type}{batch_size} messages for cohort {idx}/{total_cohorts} (cohort_id={cohort_id})",- )- logger.info(- f"Flushing {batch_type}batch of {batch_size} messages for cohort {cohort_id}",- cohort_id=cohort_id,- batch_size=batch_size,- )-- # Time the Kafka flush operation- flush_start_time = time.monotonic()- await asyncio.to_thread(kafka_producer.flush)- flush_duration = time.monotonic() - flush_start_time-- KAFKA_FLUSH_DURATION_HISTOGRAM.labels(percentile_bucket=percentile_bucket).observe(flush_duration)-- # Check for failures in this batch- failed_count = 0- for send_result in pending_messages:- try:- send_result.get(timeout=0) # Non-blocking check- except Exception as e:- logger.warning(- f"Kafka send result failure for cohort {cohort_id}: {e}",- cohort_id=cohort_id,- error=str(e),- exception_type=type(e).__name__,- )- failed_count += 1-- if failed_count > 0:- logger.error(- f"Failed to send {failed_count}/{batch_size} Kafka messages for cohort {cohort_id}",- cohort_id=cohort_id,- failed_count=failed_count,- batch_size=batch_size,- )- raise Exception(f"Failed to send {failed_count}/{batch_size} Kafka messages")-- return batch_size---@database_sync_to_async-def _batch_update_cohort_metrics(cohort_durations: dict[int, int]) -> int:- """Batch update cohort durations and realtime calculation timestamp.-- Only updates duration_ms when it changed by more than DURATION_UPDATE_RELATIVE_THRESHOLD from the previous value.- Always updates last_realtime_cohort_calculation_at for all processed cohorts.- Does NOT update last_backfill_person_properties_at - that should only be updated by the backfilling person properties workflow.-- Returns count of cohorts that had their duration updated.- """- if not cohort_durations:- return 0-- all_cohorts = list(Cohort.objects.filter(id__in=cohort_durations.keys()))- now = timezone.now()- duration_updates_count = 0-- for cohort in all_cohorts:- cohort.last_realtime_cohort_calculation_at = now-- new_duration = cohort_durations[cohort.pk]- previous_duration = cohort.last_calculation_duration_ms or 0-- # Only update duration_ms if it changed significantly- if previous_duration > 0:- percentage_change = abs(new_duration - previous_duration) / previous_duration- should_update_duration = percentage_change > DURATION_UPDATE_RELATIVE_THRESHOLD- else:- # First calculation or previous was 0, always update duration- should_update_duration = True-- if should_update_duration:- cohort.last_calculation_duration_ms = new_duration- duration_updates_count += 1-- # Single bulk_update for all cohorts — updates last_realtime_cohort_calculation_at and last_calculation_duration_ms- if all_cohorts:- Cohort.objects.bulk_update(- all_cohorts,- [- "last_realtime_cohort_calculation_at",- "last_calculation_duration_ms",- ],- )-- return duration_updates_count---def build_final_query(current_members_sql: str) -> str:- """Build the membership diff query that compares current cohort matches against stored membership.-- Uses a FULL OUTER JOIN between the current-match subquery and the latest cohort_membership- state. Only rows where exactly one side is NULL (i.e. the person entered or left) pass- the WHERE filter; unchanged members are excluded without materialising the 'unchanged' string.-- The returned SQL references the %(team_id)s and %(cohort_id)s bind params; the caller must- pass both in query_parameters when executing the query.- """- return f"""- SELECT- COALESCE(current_matches.id, previous_members.person_id) as person_id,- if(previous_members.person_id IS NULL, 'entered', 'left') as status- FROM- (- {current_members_sql}- ) AS current_matches- FULL OUTER JOIN- (- SELECT person_id, argMax(status, last_updated) as status- FROM cohort_membership- WHERE- team_id = %(team_id)s- AND cohort_id = %(cohort_id)s- GROUP BY person_id- HAVING status = 'entered'- ) previous_members ON current_matches.id = previous_members.person_id- WHERE (previous_members.person_id IS NULL) OR (current_matches.id IS NULL)- SETTINGS- join_use_nulls = 1,- -- Every GROUP BY here aggregates by person_id, which is in no source table's sort- -- key, so it builds a full in-memory hash table. On large cohorts — both the- -- single-scan path and the INTERSECT/UNION DISTINCT fall-through — this can exhaust- -- the query memory limit and OOM. Spill to disk past a fraction of that limit instead- -- of failing; this is an offline job, so slower-but-completes is the right trade-off.- -- memory_efficient bounds the distributed merge step too.- max_bytes_ratio_before_external_group_by = {EXTERNAL_GROUP_BY_MEMORY_RATIO},- distributed_aggregation_memory_efficient = 1- FORMAT JSONEachRow- """---async def process_realtime_cohort_calculation_activity(inputs: RealtimeCohortCalculationWorkflowInputs) -> None:- """Process a batch of realtime cohorts using HogQLRealtimeCohortQuery."""- bind_contextvars()- logger = LOGGER.bind()-- if inputs.cohort_id is not None:- num_cohorts_desc = "1 cohort"- elif inputs.cohort_ids is not None:- num_cohorts_desc = f"{len(inputs.cohort_ids)} cohorts"- else:- num_cohorts_desc = "0 cohorts"-- logger.info("Starting realtime cohort calculation workflow", num_cohorts_desc=num_cohorts_desc)-- async with Heartbeater(details=(f"Starting to process {num_cohorts_desc}",)) as heartbeater:- start_time = time.monotonic()- cohort_durations = {}- percentile_bucket = get_percentile_bucket_label(inputs.duration_percentile_min, inputs.duration_percentile_max)-- @database_sync_to_async- def get_cohorts():- # Handle backward compatibility: single cohort_id- if inputs.cohort_id is not None:- queryset = Cohort.objects.filter(- deleted=False, cohort_type=CohortType.REALTIME, id=inputs.cohort_id- ).select_related("team")- return list(queryset)-- # Handle new approach: specific cohort IDs provided by coordinator- if inputs.cohort_ids is not None:- # Filter by the specific cohort IDs, maintaining order for consistent processing- queryset = (- Cohort.objects.filter(- deleted=False,- cohort_type=CohortType.REALTIME,- id__in=inputs.cohort_ids,- )- .select_related("team")- .order_by("id") # Critical: ordered by ID for consistent processing- )- return list(queryset)-- # No cohorts specified- return []-- cohorts: list[Cohort] = await get_cohorts()-- cohorts_count = 0- kafka_producer = get_producer(topic=KAFKA_COHORT_MEMBERSHIP_CHANGED)-- @database_sync_to_async- def build_query(cohort_obj):- realtime_query = HogQLRealtimeCohortQuery(cohort=cohort_obj, team=cohort_obj.team)- current_members_query = realtime_query.get_query()- # Note: restricted_properties is not set here (defaults to None), so the printer- # will call get_restricted_properties_for_team and apply any property access-control- # rules configured for the team. This is intentionally different from the backfill- # path in hogql_compile.py, which bypasses restrictions to match raw-SQL semantics.- # Realtime cohort calculation should respect property restrictions.- hogql_context = HogQLContext(- team_id=cohort_obj.team_id,- enable_select_queries=True,- limit_context=LimitContext.COHORT_CALCULATION,- )- current_members_sql, _ = prepare_and_print_ast(current_members_query, hogql_context, "clickhouse")- return current_members_sql, hogql_context.values-- for idx, cohort in enumerate(cohorts, 1):- heartbeater.details = (f"Processing cohort {idx}/{len(cohorts)} (cohort_id={cohort.pk})",)- logger.info("Processing cohort", cohort_index=idx, total_cohorts=len(cohorts), cohort_id=cohort.pk)-- # Start timing the entire cohort processing (query + Kafka production + flushing)- cohort_start_time = time.monotonic()-- try:- # Time the query building process- query_build_start_time = time.monotonic()- current_members_sql, query_params = await build_query(cohort)- query_build_duration = time.monotonic() - query_build_start_time- QUERY_BUILD_DURATION_HISTOGRAM.labels(percentile_bucket=percentile_bucket).observe(query_build_duration)-- query_params = {- **query_params,- "team_id": cohort.team_id,- "cohort_id": cohort.pk,- }-- final_query = build_final_query(current_members_sql)-- heartbeater.details = (f"Executing query for cohort {idx}/{len(cohorts)} (cohort_id={cohort.pk})",)-- with tags_context(- team_id=cohort.team_id,- cohort_id=cohort.pk,- feature=Feature.BEHAVIORAL_COHORTS,- product=Product.MESSAGING,- query_type="realtime_cohort_calculation",- ):- status_counts = {"entered": 0, "left": 0}- pending_kafka_messages = []- # Count of messages successfully produced to Kafka (pending flush), excluding failed produce attempts- total_messages = 0- total_flushed = 0-- logger.info("Executing query for cohort", cohort_id=cohort.pk)-- # Time the ClickHouse query execution- query_start_time = time.monotonic()- query_execution_complete = False-- # Track row processing rate (will be set when first row arrives)- row_processing_start_time = None- rows_processed = 0-- async with get_messaging_client(team_id=cohort.team_id) as client:- try:- async for row in client.stream_query_as_jsonl(- final_query,- query_parameters=query_params,- ):- # Record query execution time on first result (when streaming starts)- if not query_execution_complete:- query_duration = time.monotonic() - query_start_time- COHORT_QUERY_EXECUTION_DURATION_HISTOGRAM.labels(- percentile_bucket=percentile_bucket- ).observe(query_duration)- query_execution_complete = True- # Start row processing timer now that query is complete- row_processing_start_time = time.monotonic()- person_id = row["person_id"]- status = row["status"]- status_counts[status] += 1- rows_processed += 1- payload = {- "team_id": cohort.team_id,- "cohort_id": cohort.pk,- "person_id": str(person_id),- # DateTime64(6) format required for Kafka JSONEachRow parsing into ClickHouse- "last_updated": dt.datetime.now(dt.UTC).strftime("%Y-%m-%d %H:%M:%S.%f"),- "status": status,- }- # Produce to Kafka without blocking - collect send results for later flushing- try:- produce_start_time = time.monotonic()- send_result = kafka_producer.produce(- topic=KAFKA_COHORT_MEMBERSHIP_CHANGED,- key=payload["person_id"],- data=payload,- )- produce_duration = time.monotonic() - produce_start_time- # Sample every 1000th row to reduce histogram overhead for large cohorts- if total_messages % KAFKA_PRODUCE_METRIC_SAMPLE_RATE == 0:- KAFKA_PRODUCE_DURATION_HISTOGRAM.labels(- percentile_bucket=percentile_bucket- ).observe(produce_duration)-- pending_kafka_messages.append(send_result)- total_messages += 1-- # Flush in batches to allow heartbeats- if len(pending_kafka_messages) >= FLUSH_BATCH_SIZE:- flushed = await flush_kafka_batch(- kafka_producer,- pending_kafka_messages,- cohort.pk,- idx,- len(cohorts),- heartbeater,- logger,- percentile_bucket,- )- total_flushed += flushed- pending_kafka_messages.clear()-- except Exception as e:- logger.warning(- f"Failed to produce Kafka message for person {payload['person_id']} in cohort {cohort.pk}: {e}",- cohort_id=cohort.pk,- person_id=payload["person_id"],- error=str(e),- )- # Continue processing even if Kafka produce fails- finally:- # Ensure query execution time is recorded even for empty results or failures- if not query_execution_complete:- query_duration = time.monotonic() - query_start_time- COHORT_QUERY_EXECUTION_DURATION_HISTOGRAM.labels(- percentile_bucket=percentile_bucket- ).observe(query_duration)-- # Flush any remaining messages- if pending_kafka_messages:- flushed = await flush_kafka_batch(- kafka_producer,- pending_kafka_messages,- cohort.pk,- idx,- len(cohorts),- heartbeater,- logger,- percentile_bucket,- is_final=True,- )- total_flushed += flushed-- # Calculate and record row processing rate- if rows_processed > 0 and row_processing_start_time is not None:- row_processing_duration = time.monotonic() - row_processing_start_time- if row_processing_duration > 0:- rows_per_second = rows_processed / row_processing_duration- ROW_PROCESSING_RATE_HISTOGRAM.labels(percentile_bucket=percentile_bucket).observe(- rows_per_second- )-- logger.info(- f"Successfully flushed {total_flushed} total messages for cohort {cohort.pk}",- cohort_id=cohort.pk,- total_messages=total_messages,- total_flushed=total_flushed,- rows_processed=rows_processed,- )-- if status_counts["entered"] > 0:- get_membership_changed_metric("entered", percentile_bucket).add(status_counts["entered"])- if status_counts["left"] > 0:- get_membership_changed_metric("left", percentile_bucket).add(status_counts["left"])-- # Calculate full cohort processing duration (not just query time)- # Includes: query execution + Kafka message production + message flushing- cohort_end_time = time.monotonic()- duration_ms = int((cohort_end_time - cohort_start_time) * 1000)- duration_seconds = duration_ms / 1000-- # Log slow cohorts for investigation- if duration_seconds > 10:- logger.warning(- f"Slow cohort detected: cohort {cohort.pk} took {duration_seconds:.1f}s to process",- cohort_id=cohort.pk,- duration_seconds=duration_seconds,- duration_ms=duration_ms,- team_id=cohort.team_id,- cohort_name=cohort.name,- is_slow_cohort=True,- )-- # Record total cohort calculation duration- COHORT_CALCULATION_TOTAL_DURATION_HISTOGRAM.labels(percentile_bucket=percentile_bucket).observe(- cohort_end_time - cohort_start_time- )-- # Store duration for batch update at the end- cohort_durations[cohort.pk] = duration_ms-- logger.info(- f"Cohort {cohort.pk} processing completed",- cohort_id=cohort.pk,- duration_ms=duration_ms,- duration_seconds=duration_seconds,- )-- get_cohort_calculation_success_metric().add(1)- cohorts_count += 1- except Exception as e:- get_cohort_calculation_failure_metric().add(1)- logger.exception(- f"Error calculating cohort {cohort.pk}: {type(e).__name__}: {str(e)}",- cohort_id=cohort.pk,- error_type=type(e).__name__,- error_message=str(e),- )-- # Batch update all cohort durations at once- if cohort_durations:- batch_update_start = time.monotonic()- duration_updates_count = await _batch_update_cohort_metrics(cohort_durations)- batch_update_duration = time.monotonic() - batch_update_start-- # Record batch update timing- COHORT_DURATION_UPDATE_HISTOGRAM.labels(percentile_bucket=percentile_bucket).observe(batch_update_duration)-- logger.info(- f"Batch duration update completed: {duration_updates_count}/{len(cohort_durations)} cohorts had duration updated",- cohorts_processed=len(cohort_durations),- duration_updates=duration_updates_count,- batch_update_duration_ms=int(batch_update_duration * 1000),- )-- end_time = time.monotonic()- duration_seconds = end_time - start_time- duration_minutes = duration_seconds / 60-- heartbeater.details = (f"Completed: processed {cohorts_count} cohorts in {duration_minutes:.1f} minutes",)-- # Record total child workflow duration- CHILD_WORKFLOW_TOTAL_DURATION_HISTOGRAM.labels(percentile_bucket=percentile_bucket).observe(duration_seconds)-- logger.info(- f"Completed processing: processed {cohorts_count} cohorts in {duration_minutes:.1f} minutes ({duration_seconds:.1f} seconds)",- cohorts_processed=cohorts_count,- duration_seconds=duration_seconds,- duration_minutes=duration_minutes,- range_info=num_cohorts_desc,- )--[email protected](name="realtime-cohort-calculation")-class RealtimeCohortCalculationWorkflow(PostHogWorkflow):- """Child workflow that processes realtime cohort calculations."""-- @staticmethod- def parse_inputs(inputs: list[str]) -> RealtimeCohortCalculationWorkflowInputs:- """Parse inputs from the management command CLI."""- return RealtimeCohortCalculationWorkflowInputs()-- @temporalio.workflow.run- async def run(self, inputs: RealtimeCohortCalculationWorkflowInputs) -> None:- """Run the workflow to process realtime cohort calculations."""- workflow_logger = temporalio.workflow.logger- if inputs.cohort_id is not None:- workflow_logger.info(- f"Starting realtime cohort calculation child workflow for cohort_id={inputs.cohort_id}"- )- elif inputs.cohort_ids is not None:- workflow_logger.info(- f"Starting realtime cohort calculation child workflow for {len(inputs.cohort_ids)} cohorts: {inputs.cohort_ids[:10]}{'...' if len(inputs.cohort_ids) > 10 else ''}"- )- else:- workflow_logger.info("Starting realtime cohort calculation child workflow for empty batch")-- # Process the batch of actions- await temporalio.workflow.execute_activity(- process_realtime_cohort_calculation_activity,- inputs,- start_to_close_timeout=dt.timedelta(minutes=60),- heartbeat_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=3,- initial_interval=dt.timedelta(seconds=5),- maximum_interval=dt.timedelta(seconds=30),- ),- )-- workflow_logger.info("Child workflow completed")diff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.pydeleted file mode 100644index 41144beb0cd7..000000000000--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow_coordinator.py+++ /dev/null@@ -1,586 +0,0 @@-import math-import random-import asyncio-import datetime as dt-import dataclasses-from typing import Any, Optional, TypedDict--from django.conf import settings-from django.db.models import F-from django.utils import timezone--import temporalio.common-import temporalio.activity-import temporalio.workflow-from temporalio.common import MetricHistogramFloat--from posthog.sync import database_sync_to_async-from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.logger import get_logger-from posthog.temporal.messaging.constants import get_child_workflow_id, get_percentile_bucket_label-from posthog.temporal.messaging.quantiles_storage import get_cached_quantiles_or_calculate-from posthog.temporal.messaging.realtime_cohort_calculation_workflow import (- RealtimeCohortCalculationWorkflow,- RealtimeCohortCalculationWorkflowInputs,-)--from products.cohorts.backend.models.cohort import Cohort, CohortType--LOGGER = get_logger(__name__)---def get_coordinator_duration_histogram(percentile_bucket: str) -> MetricHistogramFloat:- """Histogram for coordinator workflow total duration by percentile bucket."""- return (- temporalio.workflow.metric_meter()- .with_additional_attributes({"percentile_bucket": percentile_bucket})- .create_histogram_float(- "realtime_cohort_coordinator_duration_seconds",- "Total duration of coordinator workflow execution in seconds",- "s",- )- )---class QueryPercentileThresholdsInput:- """Input for querying percentile thresholds."""-- min_percentile: Optional[float] = None # e.g., 0.0 for p0- max_percentile: Optional[float] = None # e.g., 90.0 for p90---class QueryPercentileThresholds:- """Query duration percentile thresholds for cohort filtering."""-- min_threshold_ms: int = 0 # Threshold for the minimum percentile (milliseconds)- max_threshold_ms: int = 0 # Threshold for the maximum percentile (milliseconds)---class CohortSelectionActivityInput:- """Combined input for get_realtime_cohort_selection_activity."""-- coordinator_inputs: "RealtimeCohortCalculationCoordinatorWorkflowInputs"- query_percentile_thresholds: QueryPercentileThresholds | None = None---def _apply_duration_filtering(queryset, thresholds: QueryPercentileThresholds | None, is_p100: bool = False):- """Apply duration filtering to cohort queryset based on percentile thresholds.-- Args:- queryset: Django queryset of Cohort objects- thresholds: Percentile thresholds containing min/max duration bounds-- Returns:- Filtered queryset-- Note:- - When is_p100=True, only lower bound is applied and NULL durations are included- - This allows new cohorts (without duration data) to be included in the slowest tier- """- if not thresholds:- return queryset-- min_threshold_ms = thresholds.min_threshold_ms- max_threshold_ms = thresholds.max_threshold_ms-- # Special case: if this is p100 (no upper limit), only apply lower bound- # and include cohorts without duration data (NULL values)- if is_p100:- # Include cohorts that are either:- # 1. Have duration >= min_threshold, OR- # 2. Have NULL duration (haven't been calculated yet)- from django.db.models import Q-- filter_condition = Q(last_calculation_duration_ms__gte=min_threshold_ms) | Q(- last_calculation_duration_ms__isnull=True- )- return queryset.filter(filter_condition)- else:- # Normal case: apply both upper and lower bounds- # Only include cohorts with duration data in the specified range-- # Handle edge case: when all cohorts have identical/similar durations,- # quantile boundaries may be identical (min_threshold_ms == max_threshold_ms).- # Using __lt would match zero rows, so use __lte for the upper bound instead.- if min_threshold_ms == max_threshold_ms:- return queryset.filter(- last_calculation_duration_ms__gte=min_threshold_ms, last_calculation_duration_ms__lte=max_threshold_ms- )- else:- return queryset.filter(- last_calculation_duration_ms__gte=min_threshold_ms, last_calculation_duration_ms__lt=max_threshold_ms- )---class WorkflowConfig(TypedDict):- """Type definition for workflow configuration."""-- id: str- inputs: RealtimeCohortCalculationWorkflowInputs- index: int---class RealtimeCohortCalculationCoordinatorWorkflowInputs:- """Inputs for the coordinator workflow that spawns child workflows."""-- parallelism: int = 10 # Number of child workflows to spawn- workflows_per_batch: int = 5 # Number of workflows to start per batch- batch_delay_minutes: int = 5 # Delay between batches in minutes- cohort_id: Optional[int] = None # Filter to a specific cohort_id (optional)- # Teams that should process all cohorts, and global percentage for teams not in team_ids- team_ids: Optional[set[int]] = (- None # Teams that process all cohorts (if empty/None, all teams use global_percentage)- )- global_percentage: Optional[float] = (- None # Percentage of cohorts for non-listed teams, or for all teams if team_ids is empty/None- )- duration_percentile_min: Optional[float] = None # Minimum duration percentile threshold (e.g., 0.0)- duration_percentile_max: Optional[float] = None # Maximum duration percentile threshold (e.g., 90.0)-- # Note: __post_init__ was removed to ensure Temporal workflow determinism.- # Django settings values (team_ids, global_percentage) are now loaded at schedule- # creation time rather than during deserialization to prevent non-deterministic- # behavior across workers and during replays.-- @property- def properties_to_log(self) -> dict[str, Any]:- return {- "parallelism": self.parallelism,- "workflows_per_batch": self.workflows_per_batch,- "batch_delay_minutes": self.batch_delay_minutes,- "cohort_id": self.cohort_id,- "team_ids": list(self.team_ids) if self.team_ids else [],- "global_percentage": self.global_percentage,- "duration_percentile_min": self.duration_percentile_min,- "duration_percentile_max": self.duration_percentile_max,- }---class RealtimeCohortSelectionResult:- """Result from selecting cohorts with filtering applied."""-- cohort_ids: list[int]---async def calculate_percentile_thresholds(- inputs: QueryPercentileThresholdsInput,-) -> QueryPercentileThresholds | None:- """Calculate percentile thresholds using cached quantiles to ensure consistency across workflows."""-- @database_sync_to_async- def get_thresholds():- try:- # Get cohorts with recent duration data (past 24 hours)- recent_cohorts = Cohort.objects.filter(- last_calculation__gte=timezone.now() - dt.timedelta(hours=24),- last_calculation_duration_ms__isnull=False,- last_calculation_duration_ms__gt=0,- deleted=False,- ).values_list("last_calculation_duration_ms", flat=True)-- if not recent_cohorts:- return None-- durations_list = list(recent_cohorts)-- # Calculate specific percentile thresholds- min_percentile = inputs.min_percentile- max_percentile = inputs.max_percentile-- # Get quantiles from cache or calculate atomically- # This ensures all workflows use the same percentile boundaries- # Check cache first even if current query has insufficient data- cached = get_cached_quantiles_or_calculate(durations_list)-- if cached is None:- LOGGER.warning("Failed to get or calculate quantiles")- # Emit metric for monitoring quantiles unavailability.- # This runs inside an activity, so use the activity meter rather than the- # workflow meter (which would raise outside a workflow event loop).- try:- quantiles_unavailable_counter = temporalio.activity.metric_meter().create_counter(- "quantiles_unavailable", "Count of times quantiles were unavailable for percentile calculations"- )- quantiles_unavailable_counter.add(1)- except RuntimeError:- # Not in activity context (e.g., during tests), skip metric- pass- return None-- quantiles = cached.quantiles- cached_max = cached.max_value-- # Special handling for p0: use 0 instead of calculating from data- if min_percentile is None or min_percentile <= 0.0:- min_threshold = 0- elif min_percentile >= 99.9:- # p100 case - use cached max so all workflows sharing this cache entry- # get identical p100 boundaries even if current durations_list differs.- min_threshold = cached_max- else:- # For percentiles 1-99, quantiles[0] is p1, quantiles[1] is p2, etc.- min_threshold = int(quantiles[int(min_percentile) - 1])-- # Calculate max threshold- if max_percentile is None or max_percentile >= 99.9:- # p100 case - use cached max for cross-workflow consistency.- max_threshold = cached_max- else:- # For percentiles 1-99, quantiles[0] is p1, quantiles[1] is p2, etc.- max_threshold = int(quantiles[int(max_percentile) - 1])-- return QueryPercentileThresholds(- min_threshold_ms=min_threshold,- max_threshold_ms=max_threshold,- )-- except (TypeError, ValueError, IndexError) as e:- LOGGER.warning(- "Failed to calculate percentile thresholds from cached quantiles",- error=str(e),- error_type=type(e).__name__,- )- return None-- return await get_thresholds()---async def get_query_percentile_thresholds_activity(- inputs: QueryPercentileThresholdsInput,-) -> QueryPercentileThresholds | None:- """Get query duration percentile thresholds by calculating directly from duration data."""- return await calculate_percentile_thresholds(inputs)---async def get_realtime_cohort_selection_activity(- activity_inputs: CohortSelectionActivityInput,-) -> RealtimeCohortSelectionResult:- """Get the actual list of cohort IDs to process based on filtering criteria."""-- # Extract values from combined input- inputs = activity_inputs.coordinator_inputs- query_percentile_thresholds = activity_inputs.query_percentile_thresholds-- @database_sync_to_async- def get_selected_cohort_ids():- # Log duration percentile filtering status- thresholds = query_percentile_thresholds-- # If cohort_id is specified, just return that specific cohort ID if it exists- # (No duration filtering when manually specifying cohort_id via Django command)- if inputs.cohort_id is not None:- cohort_exists = Cohort.objects.filter(- deleted=False, cohort_type=CohortType.REALTIME, id=inputs.cohort_id- ).exists()- return [inputs.cohort_id] if cohort_exists else []-- selected_cohort_ids = []-- # Step 1: Add cohort IDs for teams that should process everything- if inputs.team_ids:- # Filter out invalid team IDs- valid_team_ids = [team_id for team_id in inputs.team_ids if isinstance(team_id, int) and team_id > 0]-- if valid_team_ids:- # Single query for all valid teams instead of N queries- team_cohort_queryset = Cohort.objects.filter(- deleted=False, cohort_type=CohortType.REALTIME, team_id__in=valid_team_ids- )- # Apply duration filtering only in scheduled mode (when percentile thresholds are available)- if thresholds and (- inputs.duration_percentile_min is not None or inputs.duration_percentile_max is not None- ):- team_cohort_queryset = _apply_duration_filtering(- team_cohort_queryset,- thresholds,- is_p100=(inputs.duration_percentile_max is not None and inputs.duration_percentile_max >= 99.9),- )- team_cohort_ids = list(- team_cohort_queryset.order_by(- F("last_calculation_duration_ms").asc(nulls_last=True), "id"- ).values_list("id", flat=True)- )-- selected_cohort_ids.extend(team_cohort_ids)-- # Step 2: Add sampled cohort IDs for global percentage (other teams)- if inputs.global_percentage and inputs.global_percentage > 0.0 and inputs.global_percentage <= 1.0:- # Get cohort IDs from teams not in the force list- if inputs.team_ids:- other_teams_queryset = Cohort.objects.filter(deleted=False, cohort_type=CohortType.REALTIME).exclude(- team_id__in=inputs.team_ids- )- else:- other_teams_queryset = Cohort.objects.filter(deleted=False, cohort_type=CohortType.REALTIME)-- # Apply duration filtering only in scheduled mode (when percentile thresholds are available)- if thresholds and (- inputs.duration_percentile_min is not None or inputs.duration_percentile_max is not None- ):- other_teams_queryset = _apply_duration_filtering(- other_teams_queryset,- thresholds,- is_p100=(inputs.duration_percentile_max is not None and inputs.duration_percentile_max >= 99.9),- )- other_teams_cohort_ids = list(- other_teams_queryset.order_by(F("last_calculation_duration_ms").asc(nulls_last=True), "id").values_list(- "id", flat=True- )- )-- if other_teams_cohort_ids:- # Apply global percentage with random sampling- num_to_include = int(len(other_teams_cohort_ids) * inputs.global_percentage)- if num_to_include > 0:- # Randomly sample cohorts to ensure fair distribution over time- selected_other_cohort_ids = random.sample(other_teams_cohort_ids, num_to_include)- selected_cohort_ids.extend(selected_other_cohort_ids)-- # Step 3: Remove duplicates while preserving order- seen_ids = set()- unique_cohort_ids = []- for cohort_id in selected_cohort_ids:- if cohort_id not in seen_ids:- seen_ids.add(cohort_id)- unique_cohort_ids.append(cohort_id)-- # Step 4: Return with duration-based ordering preserved for effective load balancing- return unique_cohort_ids-- cohort_ids = await get_selected_cohort_ids()- return RealtimeCohortSelectionResult(cohort_ids=cohort_ids)--[email protected](name="realtime-cohort-calculation-coordinator")-class RealtimeCohortCalculationCoordinatorWorkflow(PostHogWorkflow):- """Coordinator workflow that spawns multiple child workflows for true parallelism."""-- @staticmethod- def parse_inputs(inputs: list[str]) -> RealtimeCohortCalculationCoordinatorWorkflowInputs:- """Parse inputs from the management command CLI."""- from posthog.settings.schedules import (- REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE,- REALTIME_COHORT_CALCULATION_TEAMS,- )-- return RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids=REALTIME_COHORT_CALCULATION_TEAMS.copy(),- global_percentage=REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE,- )-- @temporalio.workflow.run- async def run(self, inputs: RealtimeCohortCalculationCoordinatorWorkflowInputs) -> None:- """Run the coordinator workflow that spawns child workflows."""- coordinator_start_time = temporalio.workflow.time()- percentile_bucket = get_percentile_bucket_label(inputs.duration_percentile_min, inputs.duration_percentile_max)-- workflow_logger = LOGGER.bind()- workflow_logger.info("Starting realtime cohort calculation coordinator", parallelism=inputs.parallelism)- workflow_logger.info(- "Cohort selection config", team_ids=inputs.team_ids, global_percentage=inputs.global_percentage- )-- # Log duration percentile filtering parameters- if inputs.duration_percentile_min is not None or inputs.duration_percentile_max is not None:- min_p = inputs.duration_percentile_min if inputs.duration_percentile_min is not None else 0.0- max_p = inputs.duration_percentile_max if inputs.duration_percentile_max is not None else 100.0- workflow_logger.info("Duration percentile filtering", min_percentile=min_p, max_percentile=max_p)-- # Get actual query percentile thresholds from the last 24 hours- thresholds_input = QueryPercentileThresholdsInput(- min_percentile=inputs.duration_percentile_min,- max_percentile=inputs.duration_percentile_max,- )- thresholds = await temporalio.workflow.execute_activity(- get_query_percentile_thresholds_activity,- thresholds_input,- start_to_close_timeout=dt.timedelta(minutes=2),- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),- )- if thresholds:- workflow_logger.info(- f"Query duration thresholds from last 24h: p{min_p}={thresholds.min_threshold_ms / 1000:.2f}s, "- f"p{max_p}={thresholds.max_threshold_ms / 1000:.2f}s"- )- else:- workflow_logger.info(- f"Duration percentile filtering p{min_p}-p{max_p}: disabled (no historical query data)"- )- else:- workflow_logger.info("Duration percentile filtering: disabled (processing all cohorts)")- thresholds = None-- # Early exit for higher percentile schedules when insufficient duration data- # This prevents tripling the workload during feature launch when all schedules- # would otherwise process every cohort- if thresholds is None and inputs.duration_percentile_min is not None and inputs.duration_percentile_min >= 90.0:- min_p = inputs.duration_percentile_min if inputs.duration_percentile_min is not None else 0.0- max_p = inputs.duration_percentile_max if inputs.duration_percentile_max is not None else 100.0- workflow_logger.info(- f"Skipping p{min_p}-p{max_p} schedule execution: insufficient duration data for percentile filtering"- )- return-- # Early exit for higher percentile schedules when all durations are identical- # This prevents multiple schedules from processing the same cohorts when- # min_threshold_ms == max_threshold_ms (all tiers would match the same set)- if (- thresholds is not None- and thresholds.min_threshold_ms == thresholds.max_threshold_ms- and inputs.duration_percentile_min is not None- and inputs.duration_percentile_min >= 90.0- ):- min_p = inputs.duration_percentile_min if inputs.duration_percentile_min is not None else 0.0- max_p = inputs.duration_percentile_max if inputs.duration_percentile_max is not None else 100.0- workflow_logger.info(- f"Skipping p{min_p}-p{max_p} schedule execution: identical duration thresholds "- f"({thresholds.min_threshold_ms}ms) would cause duplicate processing across tiers"- )- return-- # Step 1: Get selected cohort IDs based on filtering criteria- selection_activity_input = CohortSelectionActivityInput(- coordinator_inputs=inputs,- query_percentile_thresholds=thresholds,- )- selection_result = await temporalio.workflow.execute_activity(- get_realtime_cohort_selection_activity,- selection_activity_input,- start_to_close_timeout=dt.timedelta(minutes=2),- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),- )-- all_cohort_ids = selection_result.cohort_ids-- # Check for empty results after cohort selection- if not all_cohort_ids:- workflow_logger.warning("No realtime cohorts found matching selection criteria")- return-- total_cohorts = len(all_cohort_ids)- workflow_logger.info(- f"Distributing {total_cohorts} selected cohorts across {inputs.parallelism} child workflows "- f"in batches of {inputs.workflows_per_batch} every {inputs.batch_delay_minutes} minutes"- )-- # Step 2: Distribute cohort IDs using round-robin to balance workload- # This distributes cohorts ordered by duration across workers to prevent- # any single worker from getting all the slow cohorts-- # Initialize lists for each worker- worker_cohort_lists: list[list[int]] = [[] for _ in range(inputs.parallelism)]-- # Distribute cohorts round-robin style- for idx, cohort_id in enumerate(all_cohort_ids):- worker_idx = idx % inputs.parallelism- worker_cohort_lists[worker_idx].append(cohort_id)-- # Step 3: Prepare all workflow configs with balanced cohort ID lists- workflow_configs: list[WorkflowConfig] = []- for i in range(inputs.parallelism):- worker_cohort_ids = worker_cohort_lists[i]-- if not worker_cohort_ids:- continue # Skip workers with no cohorts-- workflow_configs.append(- WorkflowConfig(- id=get_child_workflow_id(temporalio.workflow.info().workflow_id, i),- inputs=RealtimeCohortCalculationWorkflowInputs(- cohort_ids=worker_cohort_ids,- cohort_id=inputs.cohort_id, # Keep for backward compatibility- duration_percentile_min=inputs.duration_percentile_min,- duration_percentile_max=inputs.duration_percentile_max,- ),- index=i + 1,- )- )-- total_workflows = len(workflow_configs)- workflow_logger.info("Prepared workflow configurations", total_workflows=total_workflows)-- # Step 4: Launch workflows in batches and collect handles- child_workflow_handles = []- workflows_scheduled = 0- for batch_start in range(0, total_workflows, inputs.workflows_per_batch):- batch_end = min(batch_start + inputs.workflows_per_batch, total_workflows)- batch_configs = workflow_configs[batch_start:batch_end]- batch_number = (batch_start // inputs.workflows_per_batch) + 1- total_batches = math.ceil(total_workflows / inputs.workflows_per_batch)-- workflow_logger.info(- f"Starting batch {batch_number}/{total_batches}: scheduling {len(batch_configs)} workflows"- )-- # Start all workflows in current batch and collect handles- for config in batch_configs:- child_handle = await temporalio.workflow.start_child_workflow(- RealtimeCohortCalculationWorkflow.run,- config["inputs"],- id=config["id"],- task_queue=settings.MESSAGING_TASK_QUEUE,- parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,- )- child_workflow_handles.append(child_handle)- workflows_scheduled += 1-- cohort_ids = config["inputs"].cohort_ids- if cohort_ids is not None:- workflow_logger.info(- f"Scheduled workflow {config['index']} for {len(cohort_ids)} cohorts: {cohort_ids[:5]}{'...' if len(cohort_ids) > 5 else ''}"- )- else:- workflow_logger.info(- f"Scheduled workflow {config['index']} for single cohort: {config['inputs'].cohort_id}"- )-- workflow_logger.info(- f"Batch {batch_number}/{total_batches} completed: {len(batch_configs)} workflows started "- f"({workflows_scheduled}/{total_workflows} total)"- )-- # Wait before starting next batch (unless this is the last batch)- if batch_end < total_workflows:- delay_seconds = inputs.batch_delay_minutes * 60- workflow_logger.info("Waiting before starting next batch", delay_minutes=inputs.batch_delay_minutes)- await temporalio.workflow.sleep(delay_seconds)-- workflow_logger.info(- "All child workflows scheduled, waiting for completion", workflows_scheduled=workflows_scheduled- )-- # Step 5: Wait for all child workflows to complete- completed_count = 0- failed_count = 0-- workflow_logger.info("Waiting for child workflows to complete", total_workflows=len(child_workflow_handles))- for handle in asyncio.as_completed(child_workflow_handles):- try:- await handle # Get the result (raises if failed)- completed_count += 1- workflow_logger.info(- f"Child workflow completed successfully ({completed_count + failed_count}/{workflows_scheduled})"- )- except Exception as e:- failed_count += 1- workflow_logger.exception(- f"Child workflow failed ({completed_count + failed_count}/{workflows_scheduled}): {e}"- )-- coordinator_duration = temporalio.workflow.time() - coordinator_start_time- get_coordinator_duration_histogram(percentile_bucket).record(coordinator_duration)-- workflow_logger.info(- f"Coordinator completed in {coordinator_duration:.1f}s",- succeeded=completed_count,- failed=failed_count,- total_duration_seconds=coordinator_duration,- )- returndiff --git a/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py b/posthog/temporal/messaging/reconcile_precalculated_data_workflow.pydeleted file mode 100644index 9ee55cbf0b51..000000000000--- a/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py+++ /dev/null@@ -1,727 +0,0 @@-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.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.clickhouse_concurrency import get_messaging_client-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---# Default overrides lookback window, env-overridable via-# RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS. 6h was a conservative interim value sized-# for steady-state run duration, never a hard bound: nothing caps how long a run takes, so a run-# longer than the window can strand a merge until the next full_scan. Moot now that this workflow is-# unscheduled and superseded. See the block comment below.-DEFAULT_OVERRIDES_LOOKBACK_HOURS = 6---# 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: a run picks up distinct_ids-# whose override landed within the lookback window-# (RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS, default DEFAULT_OVERRIDES_LOOKBACK_HOURS)-# and repairs just their rows. A `full_scan` input ignores the window.-#-# Superseded and unscheduled. rust/cohort-stream-processor owns reconciliation now, in its-# workers/reconcile.rs and sweep/reconcile.rs, against RocksDB state rather than by re-querying-# ClickHouse. This workflow is retained only until the Python implementation is deleted, so the-# lookback no longer bounds anything: with no cadence behind it, any override older than the window-# is simply missed unless a run passes `full_scan`.-#-# If a one-off run is ever needed before this goes, note that a repair still has to land inside the-# person-overrides squash cadence (SQUASH_PERSON_OVERRIDES_SCHEDULE, weekly by default). That squash-# folds overrides into the events table and then DELETES the override rows, and precalculated_events-# is not part of it, so an override this workflow never saw is 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", DEFAULT_OVERRIDES_LOOKBACK_HOURS, 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", DEFAULT_OVERRIDES_LOOKBACK_HOURS, 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",- ):- # Hold a messaging-wide query slot for the whole streaming context (several batched- # queries with Kafka produce / eval between them). Coarse, but only team_concurrency- # (default 5) of these run at once, and waiting on the slot is backpressure, not a 202.- async with get_messaging_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", DEFAULT_OVERRIDES_LOOKBACK_HOURS, 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",- ):- # See the person-properties activity above: one slot held for the streaming context.- async with get_messaging_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/test/__init__.py b/posthog/temporal/messaging/test/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.pydeleted file mode 100644index 69ba86a3e8be..000000000000--- a/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py+++ /dev/null@@ -1,157 +0,0 @@-import datetime as dt--import pytest-from unittest.mock import AsyncMock, patch--from posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow import (- BackfillPrecalculatedEventsCoordinatorInputs,- EventDateCheckInputs,- check_day_already_backfilled_activity,- compute_day_ranges,-)-from posthog.temporal.messaging.constants import BACKFILL_EVENT_SOURCE_PREFIX---class TestEventDateCheckInputs:- def test_basic_construction(self):- inputs = EventDateCheckInputs(- team_id=1,- condition_hashes=["hash1", "hash2"],- date="2024-01-15",- )- assert inputs.team_id == 1- assert inputs.condition_hashes == ["hash1", "hash2"]- assert inputs.date == "2024-01-15"---class TestBackfillPrecalculatedEventsCoordinatorInputs:- def test_properties_to_log(self):- inputs = BackfillPrecalculatedEventsCoordinatorInputs(- team_id=1,- filter_storage_key="key",- cohort_ids=[1, 2, 3],- condition_hashes=["hash1", "hash2"],- days_to_backfill=30,- concurrent_workflows=5,- )- props = inputs.properties_to_log- assert props["team_id"] == 1- assert props["cohort_count"] == 3- assert props["days_to_backfill"] == 30- assert props["concurrent_workflows"] == 5- assert props["condition_count"] == 2-- def test_default_concurrent_workflows(self):- inputs = BackfillPrecalculatedEventsCoordinatorInputs(- team_id=1,- filter_storage_key="key",- cohort_ids=[1],- condition_hashes=["hash1"],- days_to_backfill=7,- )- assert inputs.concurrent_workflows == 5-- def test_default_ignore_backfilled_dates(self):- inputs = BackfillPrecalculatedEventsCoordinatorInputs(- team_id=1,- filter_storage_key="key",- cohort_ids=[1],- condition_hashes=["hash1"],- days_to_backfill=7,- )- assert inputs.ignore_backfilled_dates is False-- def test_ignore_backfilled_dates_in_properties_to_log(self):- inputs = BackfillPrecalculatedEventsCoordinatorInputs(- team_id=1,- filter_storage_key="key",- cohort_ids=[1],- condition_hashes=["hash1"],- days_to_backfill=7,- ignore_backfilled_dates=True,- )- props = inputs.properties_to_log- assert props["ignore_backfilled_dates"] is True---class TestCheckDayAlreadyBackfilledActivity:- @pytest.mark.asyncio- async def test_empty_condition_hashes_returns_not_backfilled(self):- inputs = EventDateCheckInputs(- team_id=1,- condition_hashes=[],- date="2024-01-15",- )- result = await check_day_already_backfilled_activity(inputs)- assert result.date == "2024-01-15"- assert result.already_backfilled is False-- @pytest.mark.asyncio- @pytest.mark.parametrize(- "condition_hashes,query_return,expected_backfilled",- [- (["hash1", "hash2"], b"2\n", True),- (["hash1", "hash2"], b"1\n", False),- (["hash1"], b"0\n", False),- ],- ids=["all_present", "partial", "none_found"],- )- async def test_backfill_status_based_on_condition_count(self, condition_hashes, query_return, expected_backfilled):- inputs = EventDateCheckInputs(- team_id=1,- condition_hashes=condition_hashes,- date="2024-01-15",- )-- mock_client = AsyncMock()- mock_client.read_query = AsyncMock(return_value=query_return)- mock_client.__aenter__ = AsyncMock(return_value=mock_client)- mock_client.__aexit__ = AsyncMock(return_value=False)-- with patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=mock_client,- ):- result = await check_day_already_backfilled_activity(inputs)-- assert result.date == "2024-01-15"- assert result.already_backfilled is expected_backfilled-- @pytest.mark.asyncio- async def test_day_check_counts_only_backfill_written_rows(self):- inputs = EventDateCheckInputs(- team_id=1,- condition_hashes=["hash1"],- date="2024-01-15",- )-- mock_client = AsyncMock()- mock_client.read_query = AsyncMock(return_value=b"1\n")- mock_client.__aenter__ = AsyncMock(return_value=mock_client)- mock_client.__aexit__ = AsyncMock(return_value=False)-- with patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=mock_client,- ):- await check_day_already_backfilled_activity(inputs)-- executed_query, executed_params = mock_client.read_query.call_args[0]- assert "source LIKE %(source_prefix)s" in executed_query- assert executed_params["source_prefix"] == f"{BACKFILL_EVENT_SOURCE_PREFIX}%"---class TestComputeDayRanges:- def test_today_is_partial_and_past_days_are_full(self):- now = dt.datetime(2026, 7, 9, 15, 30, 45, tzinfo=dt.UTC)- ranges = compute_day_ranges(now, 3)- assert ranges == [- (dt.datetime(2026, 7, 9, tzinfo=dt.UTC), now, True),- (dt.datetime(2026, 7, 8, tzinfo=dt.UTC), dt.datetime(2026, 7, 9, tzinfo=dt.UTC), False),- (dt.datetime(2026, 7, 7, tzinfo=dt.UTC), dt.datetime(2026, 7, 8, tzinfo=dt.UTC), False),- ]-- def test_single_day_backfill_is_partial(self):- now = dt.datetime(2026, 7, 9, 15, 30, 45, tzinfo=dt.UTC)- ranges = compute_day_ranges(now, 1)- assert ranges == [(dt.datetime(2026, 7, 9, tzinfo=dt.UTC), now, True)]diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_events_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_events_workflow.pydeleted file mode 100644index 93d25b1108f4..000000000000--- a/posthog/temporal/messaging/test/test_backfill_precalculated_events_workflow.py+++ /dev/null@@ -1,317 +0,0 @@-import uuid-import datetime as dt--import pytest-from unittest.mock import MagicMock, Mock, patch--import temporalio.exceptions-from confluent_kafka import KafkaException-from parameterized import parameterized-from temporalio.testing import ActivityEnvironment--from posthog.clickhouse.client import sync_execute-from posthog.models.event.util import create_event-from posthog.temporal.messaging.backfill_precalculated_events_workflow import (- BackfillPrecalculatedEventsInputs,- backfill_precalculated_events_activity,- evaluate_event_combined_filters_sync,- evaluate_event_filters_with_fallback_sync,- evaluate_event_individual_filters_sync,- flush_kafka_batch_async,- parse_event_properties,-)-from posthog.temporal.messaging.types import BehavioralEventFilter--from common.hogvm.python.operation import Operation---class TestParseEventProperties:- @parameterized.expand(- [- ("dict_input", {"key": "value"}, {"key": "value"}),- ("json_string", '{"key": "value"}', {"key": "value"}),- ("empty_dict", {}, {}),- ("none_input", None, {}),- ("invalid_json", "not json", {}),- ("json_array", "[1, 2]", {}),- ("json_number", "42", {}),- ]- )- def test_parse_event_properties(self, _name, raw_input, expected):- assert parse_event_properties(raw_input, "test-uuid") == expected---class TestFlushKafkaBatchAsync:- @pytest.mark.asyncio- async def test_empty_futures_returns_zero(self):- result = await flush_kafka_batch_async(kafka_results=[], kafka_producer=Mock(), team_id=1, logger=Mock())- assert result == 0-- @pytest.mark.asyncio- async def test_successful_batch_flush(self):- kafka_producer = Mock()- kafka_results = [Mock(), Mock()]-- with patch(- "posthog.temporal.messaging.backfill_precalculated_events_workflow.asyncio.to_thread"- ) as mock_thread:- mock_thread.return_value = None- result = await flush_kafka_batch_async(- kafka_results=kafka_results, kafka_producer=kafka_producer, team_id=1, logger=Mock()- )-- assert result == 2- mock_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):- # Bytecode that returns {"hash1": true}- bytecode = ["_H", 1, Operation.STRING, "hash1", Operation.TRUE, Operation.DICT, 1]- result = evaluate_event_combined_filters_sync(bytecode, {"event": "$pageview", "properties": {}}, "test-uuid")- assert result == {"hash1": True}-- def test_returns_empty_on_non_dict(self):- # Bytecode that returns a boolean instead of dict- bytecode = ["_H", 1, Operation.TRUE]- result = evaluate_event_combined_filters_sync(bytecode, {"event": "$pageview", "properties": {}}, "test-uuid")- assert result == {}-- def test_returns_empty_on_error(self):- result = evaluate_event_combined_filters_sync(- ["_H", 1, Operation.STRING], # Malformed bytecode- {"event": "$pageview", "properties": {}},- "test-uuid",- )- assert result == {}---class TestEvaluateEventIndividualFiltersSync:- def test_evaluates_each_filter(self):- filters = [- BehavioralEventFilter(- condition_hash="hash1",- bytecode=["_H", 1, Operation.TRUE],- cohort_ids=[1],- event_name="$pageview",- time_value=30,- time_interval="day",- ),- BehavioralEventFilter(- condition_hash="hash2",- bytecode=["_H", 1, Operation.FALSE],- cohort_ids=[2],- event_name="$pageview",- time_value=7,- time_interval="day",- ),- ]- result = evaluate_event_individual_filters_sync(filters, {"event": "$pageview", "properties": {}}, "test-uuid")- assert result == {"hash1": True, "hash2": False}-- def test_skips_failed_filters(self):- filters = [- BehavioralEventFilter(- condition_hash="hash1",- bytecode=["_H", 1, Operation.TRUE],- cohort_ids=[1],- event_name="$pageview",- time_value=30,- time_interval="day",- ),- BehavioralEventFilter(- condition_hash="hash_bad",- bytecode=["_H", 1, Operation.STRING], # Malformed- cohort_ids=[2],- event_name="$pageview",- time_value=30,- time_interval="day",- ),- ]- result = evaluate_event_individual_filters_sync(filters, {"event": "$pageview", "properties": {}}, "test-uuid")- assert result == {"hash1": True}---class TestEvaluateEventFiltersWithFallbackSync:- def test_uses_combined_when_successful(self):- bytecode = ["_H", 1, Operation.STRING, "hash1", Operation.TRUE, Operation.DICT, 1]- filters = [- BehavioralEventFilter(- condition_hash="hash1",- bytecode=["_H", 1, Operation.TRUE],- cohort_ids=[1],- event_name="$pageview",- time_value=30,- time_interval="day",- ),- ]- result = evaluate_event_filters_with_fallback_sync(- bytecode, filters, {"event": "$pageview", "properties": {}}, "test-uuid"- )- assert result == {"hash1": True}-- def test_falls_back_on_combined_error(self):- bad_bytecode = ["_H", 1, Operation.STRING] # Malformed- filters = [- BehavioralEventFilter(- condition_hash="hash1",- bytecode=["_H", 1, Operation.TRUE],- cohort_ids=[1],- event_name="$pageview",- time_value=30,- time_interval="day",- ),- ]- result = evaluate_event_filters_with_fallback_sync(- bad_bytecode, filters, {"event": "$pageview", "properties": {}}, "test-uuid"- )- assert result == {"hash1": True}---class TestBackfillPrecalculatedEventsActivity:- @pytest.mark.asyncio- async def test_missing_filters_raises_non_retryable(self):- inputs = BackfillPrecalculatedEventsInputs(- team_id=1,- filter_storage_key="nonexistent_key",- cohort_ids=[1],- start_time="2024-01-01T00:00:00+00:00",- end_time="2024-01-02T00:00:00+00:00",- )-- with (- patch(- "posthog.temporal.messaging.backfill_precalculated_events_workflow.get_event_filters",- return_value=None,- ),- patch(- "posthog.temporal.messaging.backfill_precalculated_events_workflow.asyncio.to_thread",- side_effect=lambda fn, *args: fn(*args),- ),- pytest.raises(temporalio.exceptions.ApplicationError, match="Event filters not found"),- ):- await backfill_precalculated_events_activity(inputs)-- @pytest.mark.asyncio- async def test_empty_filters_returns_zero(self):- inputs = BackfillPrecalculatedEventsInputs(- team_id=1,- filter_storage_key="some_key",- cohort_ids=[1],- start_time="2024-01-01T00:00:00+00:00",- end_time="2024-01-02T00:00:00+00:00",- )-- with (- patch(- "posthog.temporal.messaging.backfill_precalculated_events_workflow.get_event_filters",- return_value=([], [], {}),- ),- patch(- "posthog.temporal.messaging.backfill_precalculated_events_workflow.asyncio.to_thread",- side_effect=lambda fn, *args: fn(*args),- ),- ):- result = await backfill_precalculated_events_activity(inputs)-- assert result.events_processed == 0- 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(- team_id=1,- filter_storage_key="key",- cohort_ids=[1, 2, 3],- start_time="2024-01-01T00:00:00+00:00",- end_time="2024-01-02T00:00:00+00:00",- )- props = inputs.properties_to_log- assert props["team_id"] == 1- assert props["cohort_count"] == 3- assert props["start_time"] == "2024-01-01T00:00:00+00:00"- assert props["end_time"] == "2024-01-02T00:00:00+00:00"diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.pydeleted file mode 100644index de584935a8f9..000000000000--- a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py+++ /dev/null@@ -1,445 +0,0 @@-from types import TracebackType--import pytest-from unittest.mock import Mock, patch--import temporalio.exceptions--from posthog.hogql import ast--from posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow import (- BackfillPrecalculatedPersonPropertiesCoordinatorInputs,- BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow,- PersonIdRangesPageInputs,- PersonIdRangesPageResult,- get_person_id_ranges_page_activity,-)---class TestBackfillPrecalculatedPersonPropertiesCoordinatorInputs:- def test_properties_to_log(self):- inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(- team_id=123,- filter_storage_key="test-key-456",- cohort_ids=[1, 2, 3],- batch_size=500,- )-- expected = {- "team_id": 123,- "cohort_count": 3,- "cohort_ids": [1, 2, 3],- "filter_storage_key": "test-key-456",- "batch_size": 500,- "concurrent_workflows": 5,- }-- assert inputs.properties_to_log == expected-- def test_default_batch_size(self):- inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(- team_id=123,- filter_storage_key="test-key",- cohort_ids=[1],- )-- assert inputs.batch_size == 1000---class TestBackfillPrecalculatedPersonPropertiesCoordinatorWorkflow:- def test_parse_inputs_raises_not_implemented(self):- with pytest.raises(NotImplementedError):- BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow.parse_inputs(["arg1", "arg2"])-- @pytest.mark.asyncio- async def test_processes_ranges_with_concurrent_workflows(self):- inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(- team_id=123,- filter_storage_key="test-key",- cohort_ids=[1, 2],- batch_size=100,- concurrent_workflows=2,- )-- mock_workflow_info = Mock()- mock_workflow_info.workflow_id = "test-coordinator-123"-- page_result = PersonIdRangesPageResult(- ranges=[("person1", "person100")],- cursor=None,- )-- workflow = BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow()-- child_workflows_started = []-- async def mock_start_child_workflow(inputs_arg, logger, batch_num, start_id, end_id, handles):- child_workflows_started.append(- {- "batch_number": batch_num,- "start_person_id": start_id,- "end_person_id": end_id,- }- )-- with (- patch("temporalio.workflow.info", return_value=mock_workflow_info),- patch("temporalio.workflow.execute_activity", return_value=page_result),- patch.object(workflow, "_start_child_workflow_for_range", side_effect=mock_start_child_workflow),- patch("asyncio.wait", return_value=(set(), set())),- patch("temporalio.workflow.logger") as mock_logger,- ):- await workflow.run(inputs)-- assert len(child_workflows_started) == 1- assert child_workflows_started[0]["batch_number"] == 1- assert child_workflows_started[0]["start_person_id"] == "person1"- assert child_workflows_started[0]["end_person_id"] == "person100"-- log_calls = [str(call) for call in mock_logger.info.call_args_list]- assert any("completed successfully" in call for call in log_calls)-- @pytest.mark.asyncio- async def test_raises_when_child_workflow_fails(self):- inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(- team_id=123,- filter_storage_key="test-key",- cohort_ids=[1],- batch_size=100,- concurrent_workflows=2,- )-- mock_workflow_info = Mock()- mock_workflow_info.workflow_id = "test-coordinator-failure"-- page_result = PersonIdRangesPageResult(ranges=[("person1", "person100")], cursor=None)-- workflow = BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow()-- class _FailingHandle:- def __await__(self):- async def _coro():- raise RuntimeError("child boom")-- return _coro().__await__()-- failing_handle = _FailingHandle()-- async def mock_start_child_workflow(inputs_arg, logger, batch_num, start_id, end_id, handles):- handles.append(failing_handle)-- with (- patch("temporalio.workflow.info", return_value=mock_workflow_info),- patch("temporalio.workflow.execute_activity", return_value=page_result),- patch.object(workflow, "_start_child_workflow_for_range", side_effect=mock_start_child_workflow),- patch("asyncio.wait", return_value=({failing_handle}, set())),- patch("temporalio.workflow.logger"),- ):- with pytest.raises(temporalio.exceptions.ApplicationError, match="child workflows failed"):- await workflow.run(inputs)-- @pytest.mark.asyncio- async def test_handles_no_person_ranges(self):- inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(- team_id=123,- filter_storage_key="test-key",- cohort_ids=[1],- batch_size=100,- concurrent_workflows=2,- )-- mock_workflow_info = Mock()- mock_workflow_info.workflow_id = "test-coordinator-no-ranges"-- empty_page = PersonIdRangesPageResult(ranges=[], cursor=None)-- workflow = BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow()-- with (- patch("temporalio.workflow.info", return_value=mock_workflow_info),- patch("temporalio.workflow.execute_activity", return_value=empty_page),- patch("temporalio.workflow.logger") as mock_logger,- ):- await workflow.run(inputs)-- log_calls = [str(call) for call in mock_logger.info.call_args_list]- assert any("No persons found for team" in call for call in log_calls)-- @pytest.mark.asyncio- async def test_paginates_through_multiple_pages(self):- inputs = BackfillPrecalculatedPersonPropertiesCoordinatorInputs(- team_id=123,- filter_storage_key="test-key",- cohort_ids=[1],- batch_size=100,- concurrent_workflows=2,- )-- mock_workflow_info = Mock()- mock_workflow_info.workflow_id = "test-coordinator-multi-page"-- page1 = PersonIdRangesPageResult(- ranges=[("person1", "person100"), ("person101", "person200")],- cursor="person200",- )- page2 = PersonIdRangesPageResult(- ranges=[("person201", "person300")],- cursor=None,- )-- workflow = BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow()-- child_workflows_started = []- call_count = 0-- async def mock_start_child_workflow(inputs_arg, logger, batch_num, start_id, end_id, handles):- child_workflows_started.append(- {- "batch_number": batch_num,- "start_person_id": start_id,- "end_person_id": end_id,- }- )-- def mock_execute_activity(activity, activity_inputs, **kwargs):- nonlocal call_count- call_count += 1- if call_count == 1:- return page1- return page2-- with (- patch("temporalio.workflow.info", return_value=mock_workflow_info),- patch("temporalio.workflow.execute_activity", side_effect=mock_execute_activity),- patch.object(workflow, "_start_child_workflow_for_range", side_effect=mock_start_child_workflow),- patch("asyncio.wait", return_value=(set(), set())),- patch("temporalio.workflow.logger") as mock_logger,- ):- await workflow.run(inputs)-- assert len(child_workflows_started) == 3- assert child_workflows_started[0]["start_person_id"] == "person1"- assert child_workflows_started[1]["start_person_id"] == "person101"- assert child_workflows_started[2]["start_person_id"] == "person201"-- log_calls = [str(call) for call in mock_logger.info.call_args_list]- assert any("completed successfully" in call for call in log_calls)---def aiter(iterable):- """Wrap a plain iterable as an async iterator for use in tests."""-- async def _aiter():- for item in iterable:- yield item-- return _aiter()---class _AsyncClientContextManager:- def __init__(self, client: Mock) -> None:- self.client = client-- async def __aenter__(self) -> Mock:- return self.client-- async def __aexit__(- self,- exc_type: type[BaseException] | None,- exc_value: BaseException | None,- traceback: TracebackType | None,- ) -> None:- return None---class TestGetPersonIdRangesPageActivity:- """Tests for get_person_id_ranges_page_activity's HogQL AST construction."""-- @pytest.mark.asyncio- async def test_where_is_none_with_no_filters(self):- captured: dict[str, object] = {}-- async def fake_compile(node, *, team_id):- captured["node"] = node- return "SELECT 1 FORMAT JSONEachRow", {}-- mock_client = Mock()- mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter([])-- with (- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.compile_hogql_for_streaming",- side_effect=fake_compile,- ),- patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=_AsyncClientContextManager(mock_client),- ),- patch("temporalio.activity.heartbeat"),- ):- await get_person_id_ranges_page_activity(- PersonIdRangesPageInputs(team_id=1, batch_size=10, page_size=5, after_person_id=None)- )-- assert "node" in captured- node = captured["node"]- assert isinstance(node, ast.SelectQuery)- assert node.where is None- # Pagination must enumerate IDs off the raw ``person`` table with DISTINCT, not the- # ``persons`` lazy table -- otherwise ``id > cursor`` is wrapped in an unbounded- # ``id IN (...)`` subquery that GROUP BYs the whole ID tail on every page.- assert node.distinct is True- assert isinstance(node.select_from, ast.JoinExpr)- assert isinstance(node.select_from.table, ast.Field)- assert node.select_from.table.chain == ["raw_persons"]-- @pytest.mark.asyncio- async def test_where_is_single_expr_with_only_after_person_id(self):- captured: dict[str, object] = {}-- async def fake_compile(node, *, team_id):- captured["node"] = node- return "SELECT 1 FORMAT JSONEachRow", {}-- mock_client = Mock()- mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter([])-- with (- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.compile_hogql_for_streaming",- side_effect=fake_compile,- ),- patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=_AsyncClientContextManager(mock_client),- ),- patch("temporalio.activity.heartbeat"),- ):- await get_person_id_ranges_page_activity(- PersonIdRangesPageInputs(team_id=1, batch_size=10, page_size=5, after_person_id="abc-123")- )-- assert "node" in captured- node = captured["node"]- assert isinstance(node, ast.SelectQuery)- assert isinstance(node.where, ast.CompareOperation)- assert node.where.op == ast.CompareOperationOp.Gt-- @pytest.mark.asyncio- async def test_where_is_and_with_both_filters(self):- captured: dict[str, object] = {}-- async def fake_compile(node, *, team_id):- captured["node"] = node- return "SELECT 1 FORMAT JSONEachRow", {}-- mock_client = Mock()- mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter([])-- with (- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.compile_hogql_for_streaming",- side_effect=fake_compile,- ),- patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=_AsyncClientContextManager(mock_client),- ),- patch("temporalio.activity.heartbeat"),- ):- await get_person_id_ranges_page_activity(- PersonIdRangesPageInputs(- team_id=1, batch_size=10, page_size=5, after_person_id="abc-123", person_id="def-456"- )- )-- assert "node" in captured- node = captured["node"]- assert isinstance(node, ast.SelectQuery)- assert isinstance(node.where, ast.And)- assert len(node.where.exprs) == 2- ops = {e.op for e in node.where.exprs if isinstance(e, ast.CompareOperation)}- assert ast.CompareOperationOp.Gt in ops- assert ast.CompareOperationOp.Eq in ops---class TestPageActivityRowConsumption:- """Stream real rows through get_person_id_ranges_page_activity.-- The AST tests above stream zero rows, so the row-consumption code — which reads ``row["person_id"]``- and batches IDs into ranges — was never exercised. These feed real rows through it.- """-- @pytest.mark.asyncio- async def test_rows_batched_into_ranges(self):- rows = [{"person_id": f"p{i}"} for i in range(1, 5)]- mock_client = Mock()- mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter(rows)- module = "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow"- with (- patch(f"{module}.compile_hogql_for_streaming", side_effect=lambda node, *, team_id: ("SELECT 1", {})),- patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=_AsyncClientContextManager(mock_client),- ),- patch("temporalio.activity.heartbeat"),- ):- result = await get_person_id_ranges_page_activity(- PersonIdRangesPageInputs(team_id=1, batch_size=2, page_size=10, after_person_id=None)- )- assert result.ranges == [("p1", "p2"), ("p3", "p4")]- assert result.cursor is None # 4 rows < limit (20), no more data-- @pytest.mark.asyncio- async def test_has_more_data_sets_cursor(self):- # batch_size=2, page_size=1 -> limit=2; a 3rd (limit+1) row signals more data and sets the cursor.- rows = [{"person_id": f"p{i}"} for i in range(1, 4)]- mock_client = Mock()- mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter(rows)- module = "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow"- with (- patch(f"{module}.compile_hogql_for_streaming", side_effect=lambda node, *, team_id: ("SELECT 1", {})),- patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=_AsyncClientContextManager(mock_client),- ),- patch("temporalio.activity.heartbeat"),- ):- result = await get_person_id_ranges_page_activity(- PersonIdRangesPageInputs(team_id=1, batch_size=2, page_size=1, after_person_id=None)- )- assert result.ranges == [("p1", "p2")]- assert result.cursor == "p2" # last processed ID, used as the next page's after_person_id---class TestDrainCompleted:- """The coordinator surfaces child failures via _drain_completed -> ApplicationError.-- The workflow test patches asyncio.wait to (set(), set()), so the failure-counting branch was never- hit. This exercises _drain_completed directly with a failing handle.- """-- @pytest.mark.asyncio- async def test_counts_completed_and_failed_and_removes_handles(self):- class _Handle:- def __init__(self, fail: bool) -> None:- self._fail = fail-- def __await__(self):- async def _coro():- if self._fail:- raise RuntimeError("child boom")- return None-- return _coro().__await__()-- ok = _Handle(fail=False)- bad = _Handle(fail=True)- handles = [ok, bad]-- workflow = BackfillPrecalculatedPersonPropertiesCoordinatorWorkflow()- completed, failed = await workflow._drain_completed({ok, bad}, handles, Mock()) # type: ignore[arg-type] # fake handles stand in for ChildWorkflowHandle-- assert completed == 1- assert failed == 1- assert handles == [] # both drained handles removed from the in-flight listdiff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_helpers.py b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_helpers.pydeleted file mode 100644index f7a95aa00c28..000000000000--- a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_helpers.py+++ /dev/null@@ -1,565 +0,0 @@-from unittest.mock import Mock--from posthog.management.commands.backfill_precalculated_person_properties import extract_person_property_filters-from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import PersonPropertyFilter---class TestExtractPersonPropertyFilters:- """Tests for extract_person_property_filters function."""-- def test_empty_filters_returns_empty_list(self):- """When cohort has no filters, should return empty list."""- cohort = Mock()- cohort.filters = None-- result = extract_person_property_filters(cohort)-- assert result == []-- def test_filters_without_properties_returns_empty_list(self):- """When filters object exists but has no properties key, should return empty list."""- cohort = Mock()- cohort.filters = {"some_other_key": "value"}-- result = extract_person_property_filters(cohort)-- assert result == []-- def test_properties_without_values_returns_empty_list(self):- """When properties exists but has no values, should return empty list."""- cohort = Mock()- cohort.filters = {"properties": {}}-- result = extract_person_property_filters(cohort)-- assert result == []-- def test_extracts_single_person_property_filter(self):- """Should extract a single person property filter with conditionHash and bytecode."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "value": "is_set",- "operator": "is_set",- "conditionHash": "abc123",- "bytecode": ["_H", 1, 31, 32, "$host"],- }- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert isinstance(result[0], PersonPropertyFilter)- assert result[0].condition_hash == "abc123"- assert result[0].bytecode == ["_H", 1, 31, 32, "$host"]-- def test_extracts_multiple_person_property_filters(self):- """Should extract multiple person property filters from nested structure."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "hash1",- "bytecode": ["bytecode1"],- },- {- "key": "$browser",- "type": "person",- "conditionHash": "hash2",- "bytecode": ["bytecode2"],- },- ],- },- {- "type": "OR",- "values": [- {- "key": "$city",- "type": "person",- "conditionHash": "hash3",- "bytecode": ["bytecode3"],- }- ],- },- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 3- assert result[0].condition_hash == "hash1"- assert result[1].condition_hash == "hash2"- assert result[2].condition_hash == "hash3"-- def test_filters_out_non_person_type_filters(self):- """Should only include filters with type='person', excluding behavioral and other types."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "person_hash",- "bytecode": ["person_bytecode"],- },- {- "key": "$pageview",- "type": "behavioral",- "conditionHash": "behavioral_hash",- "bytecode": ["behavioral_bytecode"],- },- {- "key": "id",- "type": "cohort",- "conditionHash": "cohort_hash",- "bytecode": ["cohort_bytecode"],- },- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "person_hash"- assert result[0].bytecode == ["person_bytecode"]-- def test_skips_filters_without_condition_hash(self):- """Should skip person property filters that don't have conditionHash."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "bytecode": ["bytecode"],- # Missing conditionHash- },- {- "key": "$browser",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- },- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"-- def test_skips_filters_without_bytecode(self):- """Should skip person property filters that don't have bytecode."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "hash1",- # Missing bytecode- },- {- "key": "$browser",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- },- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"-- def test_skips_filters_with_none_condition_hash(self):- """Should skip filters where conditionHash is explicitly None."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": None,- "bytecode": ["bytecode"],- },- {- "key": "$browser",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- },- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"-- def test_skips_filters_with_none_bytecode(self):- """Should skip filters where bytecode is explicitly None."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "hash1",- "bytecode": None,- },- {- "key": "$browser",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- },- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"-- def test_skips_filters_with_empty_string_condition_hash(self):- """Should skip filters where conditionHash is empty string."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "",- "bytecode": ["bytecode"],- },- {- "key": "$browser",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- },- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"-- def test_skips_filters_with_empty_list_bytecode(self):- """Should skip filters where bytecode is empty list."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "hash1",- "bytecode": [],- },- {- "key": "$browser",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- },- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"-- def test_handles_deeply_nested_filter_structure(self):- """Should handle deeply nested OR/AND filter structures."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "deep_hash",- "bytecode": ["deep_bytecode"],- }- ],- }- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "deep_hash"-- def test_handles_mixed_valid_and_invalid_filters(self):- """Should extract only valid filters when mixed with invalid ones."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {"key": "$host", "type": "person"}, # Missing both- {- "key": "$browser",- "type": "person",- "conditionHash": "hash1",- }, # Missing bytecode- {- "key": "$city",- "type": "person",- "bytecode": ["bytecode"],- }, # Missing conditionHash- {- "key": "$country",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- }, # Valid- {- "key": "$pageview",- "type": "behavioral",- "conditionHash": "behavioral_hash",- "bytecode": ["behavioral_bytecode"],- }, # Wrong type- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"- assert result[0].bytecode == ["valid_bytecode"]-- def test_handles_values_list_with_non_dict_items(self):- """Should gracefully skip non-dict items in values list."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- None, # Invalid- "string", # Invalid- 123, # Invalid- {- "key": "$host",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- }, # Valid- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"-- def test_preserves_complex_bytecode_structure(self):- """Should preserve complex bytecode arrays as-is."""- complex_bytecode = [- "_H",- 1,- 31,- 32,- "$host",- 32,- "properties",- 32,- "person",- 1,- 3,- 12,- {"nested": "object"},- ["nested", "array"],- ]- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "complex_hash",- "bytecode": complex_bytecode,- }- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].bytecode == complex_bytecode- # Verify it's the same reference (not copied)- assert result[0].bytecode is complex_bytecode-- def test_handles_missing_values_key_in_group(self):- """Should handle groups that don't have a 'values' key."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {"type": "OR"}, # Missing 'values' key- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "valid_hash",- "bytecode": ["valid_bytecode"],- }- ],- },- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 1- assert result[0].condition_hash == "valid_hash"-- def test_returns_distinct_filter_objects(self):- """Should return distinct PersonPropertyFilter objects for each filter."""- cohort = Mock()- cohort.filters = {- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$host",- "type": "person",- "conditionHash": "hash1",- "bytecode": ["bytecode1"],- },- {- "key": "$browser",- "type": "person",- "conditionHash": "hash2",- "bytecode": ["bytecode2"],- },- ],- }- ],- }- }-- result = extract_person_property_filters(cohort)-- assert len(result) == 2- assert result[0] is not result[1]- assert isinstance(result[0], PersonPropertyFilter)- assert isinstance(result[1], PersonPropertyFilter)diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.pydeleted file mode 100644index 6cc947145fd3..000000000000--- a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py+++ /dev/null@@ -1,766 +0,0 @@-from types import TracebackType--import pytest-from unittest.mock import Mock, patch--import temporalio.exceptions-from parameterized import parameterized--from posthog.hogql import ast-from posthog.hogql.visitor import TraversingVisitor--from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (- BackfillPrecalculatedPersonPropertiesInputs,- backfill_precalculated_person_properties_activity,- build_person_properties_select_fields,- evaluate_combined_filters_sync,- flush_kafka_batch_async,-)-from posthog.temporal.messaging.filter_storage import combine_filter_bytecodes, store_filters-from posthog.temporal.messaging.types import PersonPropertyFilter--from common.hogvm.python.execute import execute_bytecode-from common.hogvm.python.operation import Operation---class _FieldChainCollector(TraversingVisitor):- """Collect every ``ast.Field`` chain reachable from a node (e.g. inside argMax wrappers)."""-- def __init__(self) -> None:- self.chains: list[list[str | int]] = []-- def visit_field(self, node: ast.Field) -> None:- self.chains.append(list(node.chain))---def _collect_field_chains(node: ast.Expr) -> list[list[str | int]]:- collector = _FieldChainCollector()- collector.visit(node)- return collector.chains---class _NoopHeartbeater:- details: tuple[str, ...]-- def __init__(self, details: tuple[str, ...] = (), factor: int = 120) -> None:- self.details = details-- async def __aenter__(self) -> "_NoopHeartbeater":- return self-- async def __aexit__(- self,- exc_type: type[BaseException] | None,- exc_value: BaseException | None,- traceback: TracebackType | None,- ) -> None:- return None---class _AsyncClientContextManager:- def __init__(self, client: Mock) -> None:- self.client = client-- async def __aenter__(self) -> Mock:- return self.client-- async def __aexit__(- self,- exc_type: type[BaseException] | None,- exc_value: BaseException | None,- traceback: TracebackType | None,- ) -> None:- return None---def aiter(iterable):- """Wrap a sync iterable as an async iterator for mocking ``stream_query_as_jsonl``."""-- async def _aiter():- for item in iterable:- yield item-- return _aiter()---class TestFlushKafkaBatchAsync:- """Tests for the flush_kafka_batch_async helper function."""-- @pytest.mark.asyncio- async def test_empty_futures_returns_zero(self):- """When kafka_results is empty, should return 0 without flushing."""- kafka_producer = Mock()- logger = Mock()-- result = await flush_kafka_batch_async(- kafka_results=[],- kafka_producer=kafka_producer,- team_id=1,- logger=logger,- )-- assert result == 0-- @pytest.mark.asyncio- async def test_successful_batch_flush_async(self):- """Should handle successful ProduceResult objects correctly."""- kafka_producer = Mock()- logger = Mock()-- # Create mock ProduceResult objects- produce_result_1 = Mock()- produce_result_2 = Mock()- kafka_results = [produce_result_1, produce_result_2]-- with patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.asyncio.to_thread"- ) as mock_thread:- mock_thread.return_value = None-- result = await flush_kafka_batch_async(- kafka_results=kafka_results,- kafka_producer=kafka_producer,- team_id=1,- logger=logger,- )-- assert result == 2- mock_thread.assert_called_once_with(kafka_producer.flush)-- @pytest.mark.asyncio- async def test_batch_flush_with_multiple_results(self):- """Should handle multiple ProduceResult objects correctly."""- kafka_producer = Mock()- logger = Mock()-- # Create mock ProduceResult objects - all are successful since failures are handled earlier- produce_result_1 = Mock()- produce_result_2 = Mock()- produce_result_3 = Mock()- kafka_results = [produce_result_1, produce_result_2, produce_result_3]-- with patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.asyncio.to_thread"- ) as mock_thread:- mock_thread.return_value = None-- result = await flush_kafka_batch_async(- kafka_results=kafka_results,- kafka_producer=kafka_producer,- team_id=1,- logger=logger,- )-- # Should return count of all ProduceResult objects (3)- assert result == 3- mock_thread.assert_called_once_with(kafka_producer.flush)-- @pytest.mark.asyncio- async def test_batch_flush_calls_kafka_flush(self):- """Should call Kafka flush operation asynchronously."""- kafka_producer = Mock()- logger = Mock()-- # Create mock ProduceResult objects- produce_results = [Mock(), Mock()]-- with patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.asyncio.to_thread"- ) as mock_thread:- mock_thread.return_value = None-- result = await flush_kafka_batch_async(- kafka_results=produce_results,- kafka_producer=kafka_producer,- team_id=1,- logger=logger,- )-- # Should return count of ProduceResult objects and call flush- assert result == 2- mock_thread.assert_called_once_with(kafka_producer.flush)---class TestBackfillPrecalculatedPersonPropertiesActivity:- """Tests for the main backfill activity function."""-- @pytest.mark.asyncio- async def test_missing_filter_storage_key_raises_non_retryable_error(self):- """Should raise non-retryable error when filter storage key doesn't exist."""- inputs = BackfillPrecalculatedPersonPropertiesInputs(- team_id=1,- filter_storage_key="nonexistent_key",- cohort_ids=[10],- batch_size=10,- start_person_id="00000000-0000-0000-0000-000000000000",- end_person_id="ffffffff-ffff-ffff-ffff-ffffffffffff",- )-- with pytest.raises(temporalio.exceptions.ApplicationError) as exc_info:- await backfill_precalculated_person_properties_activity(inputs)-- assert exc_info.value.non_retryable is True- assert "Filters not found" in str(exc_info.value)-- @pytest.mark.asyncio- async def test_no_filters_aborts_early(self):- """Should abort early and return zero results when no filters exist."""- storage_key = store_filters([], team_id=1)-- inputs = BackfillPrecalculatedPersonPropertiesInputs(- team_id=1,- filter_storage_key=storage_key,- cohort_ids=[10],- batch_size=10,- start_person_id="00000000-0000-0000-0000-000000000000",- end_person_id="ffffffff-ffff-ffff-ffff-ffffffffffff",- )-- result = await backfill_precalculated_person_properties_activity(inputs)-- # Should return early with zero results- assert result.persons_processed == 0- assert result.events_produced == 0- assert result.events_flushed == 0- assert result.last_person_id is None-- @pytest.mark.asyncio- async def test_property_names_with_backticks_generate_safe_query(self):- """Should safely handle property names that contain backticks."""- # Create filters with a property name containing backticks- filters = [- PersonPropertyFilter(- condition_hash="backtick_condition",- bytecode=[], # Empty bytecode for test- cohort_ids=[10],- property_key="weird`property",- ),- ]-- storage_key = store_filters(filters, team_id=1)-- # This should not crash when constructing query parameters- inputs = BackfillPrecalculatedPersonPropertiesInputs(- team_id=1,- filter_storage_key=storage_key,- cohort_ids=[10],- batch_size=10,- start_person_id="00000000-0000-0000-0000-000000000000",- end_person_id="ffffffff-ffff-ffff-ffff-ffffffffffff",- )-- # Basic verification that the filter was stored correctly- assert inputs.filter_storage_key == storage_key-- def test_build_person_properties_select_fields_keeps_keys_in_field_chain(self):- malicious_property = "email') FROM person WHERE team_id != %(team_id)s UNION ALL SELECT sleep(3) --"-- select_fields, property_alias_mapping = build_person_properties_select_fields([malicious_property])-- assert property_alias_mapping == {"prop_0": malicious_property}-- # The malicious key must live inside an argmax_select field chain — never inline as a SQL- # fragment. argmax_select wraps the chain in an ``ast.Field``, keeping the key parameterized.- assert select_fields == {"prop_0": ["properties", malicious_property]}-- @pytest.mark.django_db(transaction=True)- @pytest.mark.asyncio- async def test_activity_parameterizes_property_keys_in_clickhouse_query(self):- from asgiref.sync import sync_to_async-- from posthog.models.organization import Organization- from posthog.models.team.team import Team-- organization = await sync_to_async(Organization.objects.create)(name="Test Organization")- team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)-- # No '%' here on purpose: '%' keys take the full-properties fallback (see the dedicated test- # below). This key exercises the optimized per-property path and proves a SQL-fragment key- # stays inside the ast.Field chain rather than being concatenated into the query.- malicious_property = "email') FROM person WHERE team_id != 1 UNION ALL SELECT sleep(3) --"- filters = [- PersonPropertyFilter(- condition_hash="injection_condition",- bytecode=["_H", 1, 29],- cohort_ids=[10],- property_key=malicious_property,- ),- ]- captured_ast: dict[str, object] = {}-- original_prepare_and_print_ast = __import__(- "posthog.hogql.printer", fromlist=["prepare_and_print_ast"]- ).prepare_and_print_ast-- def capturing_prepare_and_print_ast(node, context, dialect):- captured_ast["node"] = node- return original_prepare_and_print_ast(node, context, dialect)-- async def stream_query_as_jsonl(query: str, query_parameters: dict[str, object] | None = None):- if False:- yield {} # type: ignore[unreachable]-- mock_client = Mock()- mock_client.stream_query_as_jsonl = stream_query_as_jsonl-- inputs = BackfillPrecalculatedPersonPropertiesInputs(- team_id=team.id,- filter_storage_key="storage_key",- cohort_ids=[10],- batch_size=10,- start_person_id="00000000-0000-0000-0000-000000000000",- end_person_id="ffffffff-ffff-ffff-ffff-ffffffffffff",- )-- with (- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_filters_and_properties",- return_value=(filters, [malicious_property], combine_filter_bytecodes(filters)),- ),- patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=_AsyncClientContextManager(mock_client),- ),- patch(- "posthog.temporal.messaging.hogql_compile.prepare_and_print_ast",- side_effect=capturing_prepare_and_print_ast,- ),- patch("posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_producer"),- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.Heartbeater",- _NoopHeartbeater,- ),- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_person_properties_backfill_success_metric",- return_value=Mock(),- ),- ):- # The key may still produce an invalid identifier in the printer; the assertion that- # matters is that it reached the printer only inside an ast.Field chain, never as a raw- # SQL fragment.- try:- await backfill_precalculated_person_properties_activity(inputs)- except Exception:- pass-- # The malicious key must only reach the printer wrapped in an ast.Field chain.- assert "node" in captured_ast, "compile_hogql_for_streaming was never called"- node = captured_ast["node"]- assert isinstance(node, ast.SelectQuery)- # The child queries raw_persons directly (via argmax_select), not the persons lazy table.- assert isinstance(node.select_from, ast.JoinExpr)- assert isinstance(node.select_from.table, ast.Field)- assert node.select_from.table.chain == ["raw_persons"]- property_aliases = [- expr for expr in node.select if isinstance(expr, ast.Alias) and expr.alias.startswith("prop_")- ]- assert len(property_aliases) == 1- # The key lives inside an ast.Field chain (wrapped in argMax by argmax_select) — never- # concatenated into the SQL as a fragment.- prop_chains = _collect_field_chains(property_aliases[0])- assert any(chain[-2:] == ["properties", malicious_property] for chain in prop_chains)-- @pytest.mark.django_db(transaction=True)- @pytest.mark.asyncio- async def test_activity_falls_back_to_full_properties_for_percent_keys(self):- from asgiref.sync import sync_to_async-- from posthog.models.organization import Organization- from posthog.models.team.team import Team-- organization = await sync_to_async(Organization.objects.create)(name="Test Organization")- team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)-- # '%' is the one character HogQL refuses as an identifier, so the optimized per-property- # path can't be used. The backfill must fall back to selecting the full properties JSON- # rather than crashing the whole batch.- percent_property = "utm_%_source"- filters = [- PersonPropertyFilter(- condition_hash="percent_condition",- bytecode=["_H", 1, 29],- cohort_ids=[10],- property_key=percent_property,- ),- ]- captured_ast: dict[str, object] = {}-- original_prepare_and_print_ast = __import__(- "posthog.hogql.printer", fromlist=["prepare_and_print_ast"]- ).prepare_and_print_ast-- def capturing_prepare_and_print_ast(node, context, dialect):- captured_ast["node"] = node- return original_prepare_and_print_ast(node, context, dialect)-- async def stream_query_as_jsonl(query: str, query_parameters: dict[str, object] | None = None):- if False:- yield {} # type: ignore[unreachable]-- mock_client = Mock()- mock_client.stream_query_as_jsonl = stream_query_as_jsonl-- inputs = BackfillPrecalculatedPersonPropertiesInputs(- team_id=team.id,- filter_storage_key="storage_key",- cohort_ids=[10],- batch_size=10,- start_person_id="00000000-0000-0000-0000-000000000000",- end_person_id="ffffffff-ffff-ffff-ffff-ffffffffffff",- )-- with (- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_filters_and_properties",- return_value=(filters, [percent_property], combine_filter_bytecodes(filters)),- ),- patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=_AsyncClientContextManager(mock_client),- ),- patch(- "posthog.temporal.messaging.hogql_compile.prepare_and_print_ast",- side_effect=capturing_prepare_and_print_ast,- ),- patch("posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_producer"),- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.Heartbeater",- _NoopHeartbeater,- ),- patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_person_properties_backfill_success_metric",- return_value=Mock(),- ),- ):- await backfill_precalculated_person_properties_activity(inputs)-- assert "node" in captured_ast, "compile_hogql_for_streaming was never called"- node = captured_ast["node"]- assert isinstance(node, ast.SelectQuery)-- # No per-property accessors — the '%' key forced the full-properties fallback.- property_aliases = [- expr for expr in node.select if isinstance(expr, ast.Alias) and expr.alias.startswith("prop_")- ]- assert property_aliases == []-- # The full ``properties`` JSON is selected instead (argmax_select aliases it as "properties"),- # and the '%' key never appears as a field chain element anywhere in the query.- properties_aliases = [- expr for expr in node.select if isinstance(expr, ast.Alias) and expr.alias == "properties"- ]- assert len(properties_aliases) == 1- assert any(chain[-1:] == ["properties"] for chain in _collect_field_chains(properties_aliases[0]))- assert all(percent_property not in chain for chain in _collect_field_chains(node))---class TestActivityRowConsumption:- """End-to-end row streaming through the child activity.-- The other activity tests stream zero rows (``compile`` is patched and the client yields nothing),- so the row-consumption code — which now reads ``row["id"]`` and reconstructs properties from- ``prop_N`` columns — was never exercised. These feed real rows through it.- """-- def _module(self, name: str) -> str:- return f"posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.{name}"-- async def _run_with_rows(self, person_properties, rows):- """Run the activity over ``rows``; return (result, captured_query_node, produced_messages, eval_globals)."""- filters = [- PersonPropertyFilter(- condition_hash="cond1",- bytecode=["_H", 1, Operation.TRUE],- cohort_ids=[10],- property_key=person_properties[0] if person_properties else None,- )- ]-- captured: dict[str, object] = {}-- async def compile_stub(node, *, team_id):- captured["node"] = node- return "SELECT 1", {}-- eval_globals: list[dict] = []-- def eval_stub(combined_bytecode, flts, hog_globals, person_id, detailed_logging=False):- eval_globals.append(hog_globals)- return {"cond1": True}-- produced: list[dict] = []- producer = Mock()-- def _produce(**kwargs):- produced.append(kwargs["data"])- return Mock()-- producer.produce = _produce-- mock_client = Mock()- mock_client.stream_query_as_jsonl = lambda *a, **kw: aiter(rows)-- inputs = BackfillPrecalculatedPersonPropertiesInputs(- team_id=1,- filter_storage_key="storage_key",- cohort_ids=[10],- batch_size=10,- start_person_id="00000000-0000-0000-0000-000000000000",- end_person_id="ffffffff-ffff-ffff-ffff-ffffffffffff",- )-- with (- patch(- self._module("get_filters_and_properties"),- return_value=(filters, list(person_properties), combine_filter_bytecodes(filters)),- ),- patch(self._module("compile_hogql_for_streaming"), side_effect=compile_stub),- patch(- "posthog.temporal.messaging.clickhouse_concurrency.get_client",- return_value=_AsyncClientContextManager(mock_client),- ),- patch(self._module("evaluate_combined_filters_with_fallback_sync"), side_effect=eval_stub),- patch(self._module("get_producer"), return_value=producer),- patch(self._module("Heartbeater"), _NoopHeartbeater),- patch(self._module("get_person_properties_backfill_success_metric"), return_value=Mock()),- ):- result = await backfill_precalculated_person_properties_activity(inputs)-- return result, captured.get("node"), produced, eval_globals-- @pytest.mark.asyncio- async def test_optimized_rows_reconstruct_properties_and_produce(self):- # Optimized format: per-property prop_N columns, no "properties" key, person UUID under "id".- pid = "11111111-1111-1111-1111-111111111111"- rows = [{"id": pid, "prop_0": "[email protected]"}]-- result, node, produced, eval_globals = await self._run_with_rows(["email"], rows)-- # row["id"] is consumed and reconstruction maps prop_0 -> email.- assert result.persons_processed == 1- assert result.last_person_id == pid- assert eval_globals[0] == {"person": {"properties": {"email": "[email protected]"}}}- assert len(produced) == 1- assert produced[0]["person_id"] == pid- assert produced[0]["condition"] == "cond1"-- # Locks the flat single-pass query shape the child optimization depends on: WHERE filters the- # raw_persons scan before the GROUP BY, with no id-IN-subquery indirection.- assert isinstance(node, ast.SelectQuery)- assert node.where is not None- assert node.group_by is not None- assert isinstance(node.select_from, ast.JoinExpr)- assert isinstance(node.select_from.table, ast.Field)- assert node.select_from.table.chain == ["raw_persons"]-- @pytest.mark.asyncio- async def test_optimized_rows_keep_present_falsey_values_and_drop_missing(self):- # A missing key comes back as SQL NULL (None); a present falsey value comes back as a- # non-null string. The reconstruction must keep the falsey value and drop only the None,- # otherwise a present-but-falsey property silently becomes a missing key.- pid = "33333333-3333-3333-3333-333333333333"- rows = [{"id": pid, "prop_0": "", "prop_1": "0", "prop_2": "false", "prop_3": None}]-- _result, _node, _produced, eval_globals = await self._run_with_rows(["empty", "zero", "flag", "absent"], rows)-- assert eval_globals[0] == {"person": {"properties": {"empty": "", "zero": "0", "flag": "false"}}}-- @pytest.mark.asyncio- async def test_fallback_rows_use_full_properties_json(self):- # Fallback format: a "properties" JSON column is present, so the consumer parses it directly.- pid = "22222222-2222-2222-2222-222222222222"- rows = [{"id": pid, "properties": '{"email": "[email protected]"}'}]-- result, _node, produced, eval_globals = await self._run_with_rows([], rows)-- assert result.persons_processed == 1- assert result.last_person_id == pid- assert eval_globals[0] == {"person": {"properties": {"email": "[email protected]"}}}- assert len(produced) == 1---class TestCombineFilterBytecodes:- """Tests for combine_filter_bytecodes."""-- def test_single_filter(self):- filters = [- PersonPropertyFilter(- condition_hash="h1",- bytecode=["_H", 1, 31, 32, "$browser", 32, "properties", 32, "person", 1, 3, 12],- cohort_ids=[10],- property_key="$browser",- ),- ]- result = combine_filter_bytecodes(filters)- assert result[0] == "_H"- assert result[1] == 1- assert result[2] == Operation.STRING- assert result[3] == "h1"- # Body without header- assert result[4:-2] == [31, 32, "$browser", 32, "properties", 32, "person", 1, 3, 12]- # Trailing DICT- assert result[-2] == Operation.DICT- assert result[-1] == 1-- def test_multiple_filters(self):- filters = [- PersonPropertyFilter(condition_hash="h1", bytecode=["_H", 1, 29], cohort_ids=[1], property_key=None),- PersonPropertyFilter(condition_hash="h2", bytecode=["_H", 1, 30], cohort_ids=[2], property_key=None),- ]- result = combine_filter_bytecodes(filters)- assert result == ["_H", 1, Operation.STRING, "h1", 29, Operation.STRING, "h2", 30, Operation.DICT, 2]-- def test_skips_malformed_bytecodes(self):- filters = [- PersonPropertyFilter(condition_hash="bad", bytecode=["_H", 1], cohort_ids=[1], property_key=None),- PersonPropertyFilter(condition_hash="good", bytecode=["_H", 1, 29], cohort_ids=[2], property_key=None),- ]- result = combine_filter_bytecodes(filters)- assert result == ["_H", 1, Operation.STRING, "good", 29, Operation.DICT, 1]-- def test_executes_and_returns_dict(self):- filters = [- PersonPropertyFilter(condition_hash="h1", bytecode=["_H", 1, 29], cohort_ids=[1], property_key=None),- PersonPropertyFilter(condition_hash="h2", bytecode=["_H", 1, 30], cohort_ids=[2], property_key=None),- ]- combined = combine_filter_bytecodes(filters)- result = execute_bytecode(combined, {})- assert result.result == {"h1": True, "h2": False}-- @parameterized.expand(- [- ({"person": {"properties": {"$browser": "Chrome"}}}, {"browser_set": True}),- ({"person": {"properties": {}}}, {"browser_set": False}),- ]- )- def test_executes_with_person_properties(self, globals_input, expected_result):- # Bytecode for: person.properties.$browser != NULL (is_set check)- browser_bytecode = ["_H", 1, 31, 32, "$browser", 32, "properties", 32, "person", 1, 3, 12]- filters = [- PersonPropertyFilter(- condition_hash="browser_set",- bytecode=browser_bytecode,- cohort_ids=[10],- property_key="$browser",- ),- ]- combined = combine_filter_bytecodes(filters)-- result = execute_bytecode(combined, globals_input)- assert result.result == expected_result-- @parameterized.expand(- [- ({"person": {"properties": {"$browser": "Chrome"}}}, {"browser_set": True, "host_set": False}),- (- {"person": {"properties": {"$browser": "Chrome", "$host": "example.com"}}},- {"browser_set": True, "host_set": True},- ),- ]- )- def test_executes_multiple_property_filters(self, globals_input, expected_result):- browser_bytecode = ["_H", 1, 31, 32, "$browser", 32, "properties", 32, "person", 1, 3, 12]- host_bytecode = ["_H", 1, 31, 32, "$host", 32, "properties", 32, "person", 1, 3, 12]- filters = [- PersonPropertyFilter(- condition_hash="browser_set", bytecode=browser_bytecode, cohort_ids=[10], property_key="$browser"- ),- PersonPropertyFilter(- condition_hash="host_set", bytecode=host_bytecode, cohort_ids=[10], property_key="$host"- ),- ]- combined = combine_filter_bytecodes(filters)-- result = execute_bytecode(combined, globals_input)- assert result.result == expected_result-- @parameterized.expand(- [- (- "single_failing",- ["failing_condition"],- ["working_condition"],- {"working_condition": True},- ),- (- "multiple_failing",- ["fail1", "fail2"],- ["work"],- {"work": True},- ),- ]- )- def test_failing_filters_are_omitted_from_results(self, _, failing_hashes, working_hashes, expected):- """Failing filters should be omitted from results, not crash the entire execution."""- from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (- evaluate_combined_filters_with_fallback_sync,- )-- failing_bytecode = ["_H", 1, 31, 32, "nonexistent", 32, "properties", 32, "person", 1, 3, 32, "test", 13]- working_bytecode = ["_H", 1, 29] # Always true-- filters = [- PersonPropertyFilter(condition_hash=h, bytecode=failing_bytecode, cohort_ids=[i], property_key=None)- for i, h in enumerate(failing_hashes)- ] + [- PersonPropertyFilter(- condition_hash=h, bytecode=working_bytecode, cohort_ids=[len(failing_hashes) + i], property_key=None- )- for i, h in enumerate(working_hashes)- ]-- combined = combine_filter_bytecodes(filters)- result = evaluate_combined_filters_with_fallback_sync(- combined, filters, {"person": {"properties": {}}}, "test-person"- )-- assert result == expected---class TestEvaluateCombinedFiltersSync:- """Tests for evaluate_combined_filters_sync."""-- def test_returns_dict_on_success(self):- combined = ["_H", 1, Operation.STRING, "h1", 29, Operation.DICT, 1]- result = evaluate_combined_filters_sync(combined, {}, "person-1")- assert result == {"h1": True}-- def test_returns_empty_dict_on_error(self):- result = evaluate_combined_filters_sync(["_H", 1, 999], {}, "person-1")- assert result == {}-- @parameterized.expand(- [- ("enabled_success", True, {"test_condition": True}, True, False),- ("disabled", False, {"test_condition": True}, False, False),- ("enabled_non_dict", True, {}, True, True),- ]- )- @patch("posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.LOGGER")- def test_detailed_logging(self, _name, detailed, expected_result, expect_info, expect_warning, mock_logger):- if detailed and expect_warning:- combined = ["_H", 1, Operation.STRING, "not_a_dict"]- else:- combined = ["_H", 1, Operation.STRING, "test_condition", 29, Operation.DICT, 1]-- hog_globals = {"person": {"properties": {"$browser": "Chrome"}}} if detailed and not expect_warning else {}-- result = evaluate_combined_filters_sync(combined, hog_globals, "person-123", detailed_logging=detailed)-- assert result == expected_result-- if expect_info:- mock_logger.info.assert_called_once()- call_args = mock_logger.info.call_args- assert call_args[0][0] == "HogVM evaluation completed"- logged_kwargs = call_args[1]- assert logged_kwargs["person_id"] == "person-123"- else:- mock_logger.info.assert_not_called()-- if expect_warning:- mock_logger.warning.assert_called_once()- call_args = mock_logger.warning.call_args- assert call_args[0][0] == "HogVM evaluation returned non-dict result"- else:- mock_logger.warning.assert_not_called()diff --git a/posthog/temporal/messaging/test/test_filter_storage.py b/posthog/temporal/messaging/test/test_filter_storage.pydeleted file mode 100644index 49e9348e4462..000000000000--- a/posthog/temporal/messaging/test/test_filter_storage.py+++ /dev/null@@ -1,381 +0,0 @@-from unittest.mock import patch--import fakeredis--from posthog.temporal.messaging.filter_storage import (- get_event_filters,- get_filters_and_properties,- store_event_filters,- store_filters,-)-from posthog.temporal.messaging.types import BehavioralEventFilter, PersonPropertyFilter---class TestFilterStorage:- """Tests for the filter storage module."""-- def setup_method(self):- """Set up test fixtures."""- self.test_filters = [- PersonPropertyFilter(- condition_hash="age_filter_25",- bytecode=["mock_bytecode_age_25"],- cohort_ids=[100],- property_key="age",- ),- PersonPropertyFilter(- condition_hash="country_filter_us",- bytecode=["mock_bytecode_country_us"],- cohort_ids=[100, 200],- property_key="country",- ),- PersonPropertyFilter(- condition_hash="age_filter_35",- bytecode=["mock_bytecode_age_35"],- cohort_ids=[200],- property_key="age",- ),- ]- self.team_id = 123-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_store_and_get_filters_round_trip(self, mock_get_client):- """Test storing and retrieving filters works correctly."""- # Use fakeredis for testing- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- # Store filters- storage_key = store_filters(self.test_filters, self.team_id)-- # Verify key format- assert storage_key.startswith("backfill_person_properties_filters:team_123_")- assert len(storage_key) > 50 # Should contain full hash-- # Retrieve filters and properties- result = get_filters_and_properties(storage_key)-- # Verify round-trip correctness- assert result is not None- retrieved_filters, person_properties, combined_bytecode = result- assert len(retrieved_filters) == 3-- for i, retrieved_filter in enumerate(retrieved_filters):- original = self.test_filters[i]- assert retrieved_filter.condition_hash == original.condition_hash- assert retrieved_filter.bytecode == original.bytecode- assert retrieved_filter.cohort_ids == original.cohort_ids- assert retrieved_filter.property_key == original.property_key-- # Also verify person properties are extracted correctly- assert person_properties == ["age", "country"] # Sorted alphabetically-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_get_filters_and_properties_missing_key_returns_none(self, mock_get_client):- """Test that getting a non-existent key returns None."""- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- # Try to get filters with a non-existent key- result = get_filters_and_properties("backfill_person_properties_filters:team_123_nonexistent")-- assert result is None-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_ttl_behavior(self, mock_get_client):- """Test TTL expiry behavior using fakeredis."""- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- # Store filters with short TTL- storage_key = store_filters(self.test_filters, self.team_id, ttl=1)-- # Verify filters can be retrieved immediately- result = get_filters_and_properties(storage_key)- assert result is not None- retrieved_filters, person_properties, combined_bytecode = result- assert len(retrieved_filters) == 3-- # Simulate TTL expiry by deleting the key- fake_redis.delete(storage_key)-- # Verify filters are no longer retrievable- expired_result = get_filters_and_properties(storage_key)- assert expired_result is None-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_different_teams_different_keys(self, mock_get_client):- """Test that different teams get different storage keys for same filters."""- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- # Store same filters for different teams- key1 = store_filters(self.test_filters, team_id=123)- key2 = store_filters(self.test_filters, team_id=456)-- # Keys should be different due to team_id in key generation- assert key1 != key2- assert "team_123" in key1- assert "team_456" in key2-- # Both should be retrievable- result1 = get_filters_and_properties(key1)- result2 = get_filters_and_properties(key2)-- assert result1 is not None- assert result2 is not None- filters1, _, _ = result1- filters2, _, _ = result2- assert len(filters1) == len(filters2) == 3-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_identical_filters_same_key(self, mock_get_client):- """Test that identical filters for the same team produce the same key."""- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- # Store same filters twice- key1 = store_filters(self.test_filters, self.team_id)- key2 = store_filters(self.test_filters, self.team_id)-- # Should get the same key (deterministic hashing)- assert key1 == key2-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_empty_filters_list(self, mock_get_client):- """Test storing and retrieving empty filters list."""- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- # Store empty filters- storage_key = store_filters([], self.team_id)-- # Retrieve and verify- result = get_filters_and_properties(storage_key)- assert result is not None- retrieved_filters, person_properties, combined_bytecode = result- assert len(retrieved_filters) == 0- assert person_properties == [] # Empty filters should result in empty properties-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_custom_ttl(self, mock_get_client):- """Test storing with custom TTL."""- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- custom_ttl = 60 # 1 minute- storage_key = store_filters(self.test_filters, self.team_id, ttl=custom_ttl)-- # Verify the key exists- result = get_filters_and_properties(storage_key)- assert result is not None-- # Check TTL was set (fakeredis should preserve this)- ttl_remaining = fake_redis.ttl(storage_key)- assert ttl_remaining > 0- assert ttl_remaining <= custom_ttl-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_filters_with_none_property_keys(self, mock_get_client):- """Test handling filters with None property_key values."""- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- # Create filters with some None property_key values- test_filters = [- PersonPropertyFilter(- condition_hash="some_filter",- bytecode=["mock_bytecode"],- cohort_ids=[100],- property_key=None, # None property key- ),- PersonPropertyFilter(- condition_hash="age_filter",- bytecode=["mock_bytecode_age"],- cohort_ids=[100],- property_key="age",- ),- ]-- storage_key = store_filters(test_filters, self.team_id)-- # Get both filters and properties- result = get_filters_and_properties(storage_key)- assert result is not None-- retrieved_filters, person_properties, combined_bytecode = result-- # Verify person properties only includes non-None keys- assert person_properties == ["age"]-- # Verify filters are retrieved correctly- assert len(retrieved_filters) == 2- assert retrieved_filters[0].property_key is None- assert retrieved_filters[1].property_key == "age"---class TestEventFilterStorage:- def setup_method(self):- self.test_filters = [- BehavioralEventFilter(- condition_hash="pageview_hash",- bytecode=["_H", 1, 32, "$pageview"],- cohort_ids=[100],- event_name="$pageview",- time_value=30,- time_interval="day",- ),- BehavioralEventFilter(- condition_hash="purchase_hash",- bytecode=["_H", 1, 32, "purchase"],- cohort_ids=[100, 200],- event_name="purchase",- time_value=7,- time_interval="day",- ),- BehavioralEventFilter(- condition_hash="pageview_pricing_hash",- bytecode=["_H", 1, 32, "$pageview", 33, "/pricing"],- cohort_ids=[200],- event_name="$pageview",- time_value=14,- time_interval="day",- event_filters=[{"type": "event", "key": "url", "value": "/pricing", "operator": "exact"}],- ),- ]- self.team_id = 123-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_store_and_get_round_trip(self, mock_get_client):- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- storage_key = store_event_filters(self.test_filters, self.team_id)-- assert storage_key.startswith("backfill_event_filters:team_123_")- assert len(storage_key) > 50-- result = get_event_filters(storage_key)- assert result is not None-- retrieved_filters, event_names, combined_bytecodes = result- assert len(retrieved_filters) == 3-- for i, retrieved in enumerate(retrieved_filters):- original = self.test_filters[i]- assert retrieved.condition_hash == original.condition_hash- assert retrieved.bytecode == original.bytecode- assert retrieved.cohort_ids == original.cohort_ids- assert retrieved.event_name == original.event_name- assert retrieved.time_value == original.time_value- assert retrieved.time_interval == original.time_interval- assert retrieved.event_filters == original.event_filters-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_event_names_extracted_and_sorted(self, mock_get_client):- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- storage_key = store_event_filters(self.test_filters, self.team_id)- result = get_event_filters(storage_key)- assert result is not None-- _, event_names, _ = result- assert event_names == ["$pageview", "purchase"]-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_combined_bytecodes_grouped_by_event_name(self, mock_get_client):- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- storage_key = store_event_filters(self.test_filters, self.team_id)- result = get_event_filters(storage_key)- assert result is not None-- _, _, combined_bytecodes = result-- # Two groups: $pageview (2 filters) and purchase (1 filter)- assert "$pageview" in combined_bytecodes- assert "purchase" in combined_bytecodes- assert len(combined_bytecodes) == 2-- # Each combined bytecode should start with the bytecode identifier- for bytecode in combined_bytecodes.values():- assert bytecode[0] == "_H"-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_missing_key_returns_none(self, mock_get_client):- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- result = get_event_filters("backfill_event_filters:team_123_nonexistent")- assert result is None-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_different_teams_different_keys(self, mock_get_client):- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- key1 = store_event_filters(self.test_filters, team_id=123)- key2 = store_event_filters(self.test_filters, team_id=456)-- assert key1 != key2- assert "team_123" in key1- assert "team_456" in key2-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_identical_filters_same_key(self, mock_get_client):- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- key1 = store_event_filters(self.test_filters, self.team_id)- key2 = store_event_filters(self.test_filters, self.team_id)-- assert key1 == key2-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_empty_filters(self, mock_get_client):- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- storage_key = store_event_filters([], self.team_id)- result = get_event_filters(storage_key)-- assert result is not None- filters, event_names, combined_bytecodes = result- assert len(filters) == 0- assert event_names == []- assert combined_bytecodes == {}-- @patch("posthog.temporal.messaging.filter_storage.get_client")- def test_single_event_name_group(self, mock_get_client):- fake_redis = fakeredis.FakeRedis()- mock_get_client.return_value = fake_redis-- single_event_filters = [- BehavioralEventFilter(- condition_hash="hash1",- bytecode=["_H", 1, 32, "$pageview"],- cohort_ids=[100],- event_name="$pageview",- time_value=30,- time_interval="day",- ),- BehavioralEventFilter(- condition_hash="hash2",- bytecode=["_H", 1, 32, "$pageview", 33, "extra"],- cohort_ids=[200],- event_name="$pageview",- time_value=7,- time_interval="day",- ),- ]-- storage_key = store_event_filters(single_event_filters, self.team_id)- result = get_event_filters(storage_key)- assert result is not None-- _, event_names, combined_bytecodes = result- assert event_names == ["$pageview"]- assert len(combined_bytecodes) == 1- assert "$pageview" in combined_bytecodesdiff --git a/posthog/temporal/messaging/test/test_hogql_compile.py b/posthog/temporal/messaging/test/test_hogql_compile.pydeleted file mode 100644index 7f386bc0844a..000000000000--- a/posthog/temporal/messaging/test/test_hogql_compile.py+++ /dev/null@@ -1,67 +0,0 @@-import pytest-from unittest.mock import patch--from asgiref.sync import sync_to_async--from posthog.hogql import ast--from posthog.models.organization import Organization-from posthog.models.team.team import Team-from posthog.temporal.messaging.hogql_compile import compile_hogql_for_streaming--[email protected]_db(transaction=True)-class TestCompileHogqlForStreaming:- @pytest.mark.asyncio- async def test_bypasses_property_restrictions(self):- """restricted_properties=set() must skip get_restricted_properties_for_team."""- organization = await sync_to_async(Organization.objects.create)(name="Test Organization")- team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)-- node = ast.SelectQuery(- select=[ast.Alias(alias="person_id", expr=ast.Field(chain=["id"]))],- select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),- )-- with patch(- # Patch the defining module: printer/utils imports this at call time, so a patch on- # the printer.utils namespace would never intercept.- "products.access_control.backend.property_access_control.get_restricted_properties_for_team",- side_effect=AssertionError("get_restricted_properties_for_team must not be called"),- ):- sql, params = await compile_hogql_for_streaming(node, team_id=team.id)-- assert "FORMAT JSONEachRow" in sql-- @pytest.mark.asyncio- async def test_property_key_is_parameterized(self):- """Property keys must reach ClickHouse as parameters, not as unquoted SQL fragments.-- When the ``persons`` lazy table is used, HogQL generates a subquery that references the- property via ``JSONExtractRaw(person.properties, %(hogql_val_N)s, ...)`` with the key as- a parameter, and also as a backtick-quoted column alias. The backtick quoting makes the- key inert as a SQL identifier — ClickHouse treats it as a column name, not executable code.- What must never happen is the key appearing as an unquoted SQL string or code fragment.- """- organization = await sync_to_async(Organization.objects.create)(name="Test Organization")- team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)-- prop_key = "email') UNION ALL SELECT sleep(3) --"- node = ast.SelectQuery(- select=[- ast.Alias(alias="person_id", expr=ast.Field(chain=["id"])),- ast.Alias(alias="prop_0", expr=ast.Field(chain=["properties", prop_key])),- ],- select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),- )-- sql, params = await compile_hogql_for_streaming(node, team_id=team.id)-- # The prop key must appear in the params dict (for the JSONExtractRaw call).- assert prop_key in params.values()- # The prop key must not appear as an unquoted SQL fragment — any occurrence must be- # inside backtick-quoted identifiers, which ClickHouse treats as column names.- assert f"'{prop_key}'" not in sql # not a SQL string literal- assert f'"{prop_key}"' not in sql # not a double-quoted identifier- assert "UNION ALL SELECT sleep" not in sql.split("`")[::2] # not outside backtick pairs- assert "FORMAT JSONEachRow" in sqldiff --git a/posthog/temporal/messaging/test/test_parse_person_properties.py b/posthog/temporal/messaging/test/test_parse_person_properties.pydeleted file mode 100644index 1d94ce0ace85..000000000000--- a/posthog/temporal/messaging/test/test_parse_person_properties.py+++ /dev/null@@ -1,127 +0,0 @@-import json--from posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import parse_person_properties---class TestParsePersonProperties:- """Unit tests for parse_person_properties function."""-- def test_parses_valid_json_string(self):- """Should parse valid JSON string into dict."""- properties = {"email": "[email protected]", "name": "Test User"}- properties_raw = json.dumps(properties)-- result = parse_person_properties(properties_raw, "person123")-- assert result == properties-- def test_handles_dict_input(self):- """Should return dict input as-is."""- properties = {"email": "[email protected]", "name": "Test User"}-- result = parse_person_properties(properties, "person123")-- assert result == properties-- def test_handles_null_value(self):- """Should return empty dict for None input."""- result = parse_person_properties(None, "person123")-- assert result == {}-- def test_handles_empty_string(self):- """Should return empty dict for empty string and log warning."""- result = parse_person_properties("", "person123")-- assert result == {}-- def test_handles_invalid_json_string(self):- """Should return empty dict for invalid JSON and log warning."""- invalid_json = "{invalid json string"-- result = parse_person_properties(invalid_json, "person123")-- assert result == {}-- def test_handles_json_null_string(self):- """Should return empty dict for JSON 'null' string."""- result = parse_person_properties("null", "person123")-- assert result == {}-- def test_handles_empty_json_object_string(self):- """Should parse empty JSON object string."""- result = parse_person_properties("{}", "person123")-- assert result == {}-- def test_handles_empty_json_array_string(self):- """Should return empty dict for JSON array."""- result = parse_person_properties("[]", "person123")-- assert result == {}-- def test_handles_json_false_string(self):- """Should return empty dict for JSON 'false' string."""- result = parse_person_properties("false", "person123")-- assert result == {}-- def test_handles_json_zero_string(self):- """Should return empty dict for JSON '0' string."""- result = parse_person_properties("0", "person123")-- assert result == {}-- def test_handles_complex_nested_json(self):- """Should parse complex nested JSON structure."""- properties = {- "email": "[email protected]",- "metadata": {"source": "api", "tags": ["premium", "enterprise"]},- "settings": {"notifications": True, "theme": "dark"},- }- properties_raw = json.dumps(properties)-- result = parse_person_properties(properties_raw, "person123")-- assert result == properties-- def test_handles_long_invalid_json_string(self):- """Should handle very long invalid JSON strings without errors."""- long_invalid_json = "{invalid" + "x" * 200-- result = parse_person_properties(long_invalid_json, "person123")-- assert result == {}-- def test_preserves_unicode_characters(self):- """Should correctly parse JSON with unicode characters."""- properties = {"name": "测试用户", "emoji": "🎉", "special": "café"}- properties_raw = json.dumps(properties, ensure_ascii=False)-- result = parse_person_properties(properties_raw, "person123")-- assert result == properties-- def test_handles_whitespace_string(self):- """Should return empty dict for whitespace-only string."""- result = parse_person_properties(" ", "person123")-- assert result == {}-- def test_handles_numeric_string(self):- """Should return empty dict for numeric string (not valid object JSON)."""- result = parse_person_properties("42", "person123")-- assert result == {}-- def test_handles_boolean_dict_values(self):- """Should preserve boolean values in parsed dict."""- properties = {"is_active": True, "is_verified": False}- properties_raw = json.dumps(properties)-- result = parse_person_properties(properties_raw, "person123")-- assert result == properties- assert result["is_active"] is True- assert result["is_verified"] is Falsediff --git a/posthog/temporal/messaging/test/test_quantiles_integration.py b/posthog/temporal/messaging/test/test_quantiles_integration.pydeleted file mode 100644index c2ccdb9ae12e..000000000000--- a/posthog/temporal/messaging/test/test_quantiles_integration.py+++ /dev/null@@ -1,287 +0,0 @@-"""-Integration tests for quantiles storage with real Redis concurrency scenarios.--Tests actual Redis operations and thread-based concurrency to verify-our locking mechanism works in practice.-"""--import time-import threading-from concurrent.futures import ThreadPoolExecutor, as_completed--import pytest-from unittest.mock import patch--from posthog.redis import get_client-from posthog.temporal.messaging.quantiles_storage import (- CachedQuantiles,- _get_cache_key,- _get_lock_key,- get_cached_quantiles_or_calculate,- get_quantiles,- store_quantiles,-)---class TestQuantilesConcurrencyIntegration:- """Integration tests using real Redis for concurrency scenarios."""-- def setup_method(self):- """Clean up Redis before each test."""- redis_client = get_client()- # Clean up any test keys- test_keys = redis_client.keys("duration_quantiles*")- if test_keys:- redis_client.delete(*test_keys)-- def teardown_method(self):- """Clean up Redis after each test."""- redis_client = get_client()- test_keys = redis_client.keys("duration_quantiles*")- if test_keys:- redis_client.delete(*test_keys)-- def test_concurrent_quantiles_calculation_real_redis(self):- """Test that concurrent workers get consistent quantiles using real Redis."""- durations = list(range(100, 1000, 20)) # Realistic data- hour_bucket = "2024-01-15:14"-- results = []- errors = []-- def worker_function(worker_id):- """Simulate a Temporal worker calculating quantiles."""- try:- result = get_cached_quantiles_or_calculate(durations, hour_bucket, max_retries=3)- return worker_id, result- except Exception as e:- errors.append(f"Worker {worker_id}: {e}")- return worker_id, None-- # Simulate 5 workers starting simultaneously- with ThreadPoolExecutor(max_workers=5) as executor:- futures = [executor.submit(worker_function, i) for i in range(5)]-- for future in as_completed(futures):- worker_id, result = future.result()- results.append((worker_id, result))-- # Verify no errors occurred- assert len(errors) == 0, f"Errors occurred: {errors}"-- # All workers should have gotten a result- assert len(results) == 5-- # All results should be identical (consistency achieved)- first_result = results[0][1]- assert first_result is not None, "First result should not be None"-- for worker_id, result in results:- assert result is not None, f"Worker {worker_id} got None result"- assert result == first_result, f"Worker {worker_id} got different result: {result} vs {first_result}"-- # Verify the cache was actually used (should be in Redis now)- cached_result = get_quantiles(hour_bucket)- assert cached_result == first_result-- def test_lock_contention_with_real_redis(self):- """Test lock contention behavior with real Redis operations."""- hour_bucket = "2024-01-15:15"- cache_key = _get_cache_key(hour_bucket)- lock_key = _get_lock_key(hour_bucket)-- redis_client = get_client()-- # Manually acquire the lock to simulate contention- lock_acquired = redis_client.set(lock_key, "locked", nx=True, ex=300)- assert lock_acquired, "Should be able to acquire lock initially"-- try:- # Try to store quantiles while lock is held by another process- test_quantiles = [100.0, 200.0, 300.0]- result = store_quantiles(test_quantiles, max_value=400, hour_bucket=hour_bucket)-- # Should fail because lock is already held- assert result is False, "Should fail to store when lock is held"-- # Cache should still be empty- assert not redis_client.exists(cache_key), "Cache should be empty when store fails"-- finally:- # Release the lock- redis_client.delete(lock_key)-- # Now storing should succeed- result = store_quantiles(test_quantiles, max_value=400, hour_bucket=hour_bucket)- assert result is True, "Should succeed after lock is released"- assert redis_client.exists(cache_key), "Cache should exist after successful store"-- def test_cache_expiration_behavior(self):- """Test that cache expiration works correctly."""- hour_bucket = "2024-01-15:16"- test_quantiles = [100.0, 200.0, 300.0]- test_max = 400-- # Store with short TTL for testing- redis_client = get_client()- cache_key = _get_cache_key(hour_bucket)-- # Store quantiles with 1 second TTL- with patch("posthog.temporal.messaging.quantiles_storage.DEFAULT_TTL", 1):- result = store_quantiles(test_quantiles, max_value=test_max, hour_bucket=hour_bucket)- assert result is True-- # Should be retrievable immediately- cached_result = get_quantiles(hour_bucket)- assert cached_result == CachedQuantiles(quantiles=test_quantiles, max_value=test_max)-- # Wait for expiration- time.sleep(1.1)-- # Should be gone now- cached_result = get_quantiles(hour_bucket)- assert cached_result is None- assert not redis_client.exists(cache_key)-- def test_realistic_workflow_simulation(self):- """Simulate the actual scenario: p0-p50 and p50-p80 workflows starting together."""- durations = [- # Simulated cohort durations from database query- 100,- 150,- 200,- 250,- 300,- 350,- 400,- 450,- 500,- 550,- 600,- 650,- 700,- 750,- 800,- 850,- 900,- 950,- 1000,- 1100,- 1200,- 1300,- 1400,- 1500,- 1600,- 1700,- 1800,- 1900,- 2000,- ]- hour_bucket = "2024-01-15:17"-- p0_p50_result = None- p50_p80_result = None- errors = []-- def p0_p50_workflow():- """Simulate p0-p50 workflow calculating quantiles."""- nonlocal p0_p50_result- try:- cached = get_cached_quantiles_or_calculate(durations, hour_bucket)- if cached:- # Calculate p0-p50 thresholds- p50_index = 50 - 1 # quantiles[49] is p50- p0_p50_result = {"min_threshold_ms": 0, "max_threshold_ms": int(cached.quantiles[p50_index])}- except Exception as e:- errors.append(f"p0-p50 workflow error: {e}")-- def p50_p80_workflow():- """Simulate p50-p80 workflow calculating quantiles."""- nonlocal p50_p80_result- try:- cached = get_cached_quantiles_or_calculate(durations, hour_bucket)- if cached:- # Calculate p50-p80 thresholds- p50_index = 50 - 1 # quantiles[49] is p50- p80_index = 80 - 1 # quantiles[79] is p80- p50_p80_result = {- "min_threshold_ms": int(cached.quantiles[p50_index]),- "max_threshold_ms": int(cached.quantiles[p80_index]),- }- except Exception as e:- errors.append(f"p50-p80 workflow error: {e}")-- # Start both workflows simultaneously- threads = [threading.Thread(target=p0_p50_workflow), threading.Thread(target=p50_p80_workflow)]-- for thread in threads:- thread.start()-- for thread in threads:- thread.join(timeout=5) # 5 second timeout-- # Verify no errors- assert len(errors) == 0, f"Workflow errors: {errors}"-- # Both workflows should have results- assert p0_p50_result is not None, "p0-p50 workflow should have result"- assert p50_p80_result is not None, "p50-p80 workflow should have result"-- # Critical test: No overlapping thresholds (the bug we fixed)- assert p0_p50_result["max_threshold_ms"] == p50_p80_result["min_threshold_ms"], (- f"Threshold overlap detected! p0-p50 max: {p0_p50_result['max_threshold_ms']}, "- f"p50-p80 min: {p50_p80_result['min_threshold_ms']}"- )-- # Verify logical order- assert p0_p50_result["min_threshold_ms"] == 0- assert p0_p50_result["max_threshold_ms"] < p50_p80_result["max_threshold_ms"]-- def test_high_concurrency_stress_test(self):- """Stress test with many concurrent workers to verify robustness."""- durations = list(range(50, 500, 5)) # Large dataset- hour_bucket = "2024-01-15:18"- num_workers = 10-- results = []- errors = []-- def stress_worker(worker_id):- """Worker that tries to get quantiles under high concurrency."""- try:- # Add small random delay to increase contention- time.sleep(0.001 * (worker_id % 3))- result = get_cached_quantiles_or_calculate(durations, hour_bucket, max_retries=5)- return worker_id, result, time.time()- except Exception as e:- errors.append(f"Worker {worker_id}: {e}")- return worker_id, None, time.time()-- start_time = time.time()-- with ThreadPoolExecutor(max_workers=num_workers) as executor:- futures = [executor.submit(stress_worker, i) for i in range(num_workers)]-- for future in as_completed(futures):- worker_id, result, finish_time = future.result()- results.append((worker_id, result, finish_time))-- end_time = time.time()-- # Verify no errors- assert len(errors) == 0, f"Stress test errors: {errors}"-- # All workers completed successfully- assert len(results) == num_workers-- # All got same result- first_result = results[0][1]- assert first_result is not None-- for worker_id, result, _ in results:- assert result == first_result, f"Worker {worker_id} got inconsistent result"-- # Test completed in reasonable time (should not be blocked excessively)- total_time = end_time - start_time- assert total_time < 10, f"Stress test took too long: {total_time}s"diff --git a/posthog/temporal/messaging/test/test_quantiles_storage.py b/posthog/temporal/messaging/test/test_quantiles_storage.pydeleted file mode 100644index 7a5c2d7fa97f..000000000000--- a/posthog/temporal/messaging/test/test_quantiles_storage.py+++ /dev/null@@ -1,292 +0,0 @@-"""-Tests for quantiles storage module.--Tests the mathematical correctness of percentile calculations and Redis caching logic.-"""--import json-import statistics--import pytest-from unittest.mock import Mock, patch--from posthog.temporal.messaging.quantiles_storage import (- CachedQuantiles,- _get_cache_key,- _get_current_hour_bucket,- _get_lock_key,- get_cached_quantiles_or_calculate,- get_quantiles,- store_quantiles,-)---class TestQuantilesMath:- """Test the mathematical correctness of percentile calculations."""-- @pytest.mark.parametrize(- "durations,description",- [- (list(range(1, 101)), "sequential 1-100"),- (- [100, 200, 300, 500, 800, 1000, 1500, 2000, 3000, 5000, 8000, 10000, 15000, 20000, 30000],- "realistic durations",- ),- ([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], "known dataset"),- ([1000] * 50, "identical values"),- ([100, 900], "two values"),- (- [- 50,- 75,- 100,- 125,- 150,- 200,- 250,- 300,- 350,- 400,- 450,- 500,- 550,- 600,- 650,- 700,- 750,- 800,- 850,- 900,- 1000,- 1200,- 1400,- 1600,- 1800,- 2000,- 2500,- 3000,- 3500,- 4000,- 5000,- 6000,- 8000,- 10000,- 15000,- 20000,- ],- "real scenario cohort durations",- ),- ],- )- def test_percentile_math_correctness(self, durations, description):- """Test mathematical correctness of percentile calculations with various datasets."""- quantiles = statistics.quantiles(durations, n=100, method="inclusive")-- # Test tier boundaries don't overlap- p50_value = quantiles[50 - 1]- p80_value = quantiles[80 - 1]- p90_value = quantiles[90 - 1]-- p0_min = 0- p50_int = int(p50_value)- p80_int = int(p80_value)- p90_int = int(p90_value)- p100_int = int(max(durations))-- # Verify tier boundaries don't overlap- tier_boundaries = [- ("p0-p50", p0_min, p50_int),- ("p50-p80", p50_int, p80_int),- ("p80-p90", p80_int, p90_int),- ("p90-p100", p90_int, p100_int),- ]-- for i, (tier_name, tier_min, tier_max) in enumerate(tier_boundaries):- # Each tier should have min <= max- assert tier_min <= tier_max, f"{description} - {tier_name}: min ({tier_min}) should be <= max ({tier_max})"-- # Adjacent tiers should connect seamlessly- if i > 0:- prev_tier_name, prev_tier_min, prev_tier_max = tier_boundaries[i - 1]- assert prev_tier_max == tier_min, (- f"{description} - {prev_tier_name} max ({prev_tier_max}) should equal {tier_name} min ({tier_min})"- )-- # Test monotonic increase of percentiles- test_percentiles = [10, 25, 50, 75, 90, 95, 99]- prev_value = 0- for p in test_percentiles:- current_value = quantiles[p - 1]- assert prev_value <= current_value, (- f"{description} - p{p - 10 if p > 10 else 0} ({prev_value}) should be <= p{p} ({current_value})"- )- prev_value = current_value-- # Verify p100 is the actual maximum- p99 = quantiles[99 - 1]- p100 = max(durations)- assert p99 <= p100, f"{description} - p99 ({p99}) should be <= p100 ({p100})"---class TestQuantilesCache:- """Test Redis caching functionality."""-- def test_cache_key_generation(self):- """Test cache key generation is consistent."""- hour_bucket = "2024-01-15:14"- expected_key = "duration_quantiles:2024-01-15:14"- assert _get_cache_key(hour_bucket) == expected_key-- def test_lock_key_generation(self):- """Test lock key generation is consistent."""- hour_bucket = "2024-01-15:14"- expected_key = "duration_quantiles_lock:2024-01-15:14"- assert _get_lock_key(hour_bucket) == expected_key-- def test_current_hour_bucket_format(self):- """Test 2-hour bucket format is correct."""- with patch("posthog.temporal.messaging.quantiles_storage.dt") as mock_dt:- # Test hour 14 (even) -> bucket starts at 14- mock_now = Mock()- mock_now.hour = 14- mock_now.strftime.return_value = "2024-01-15:14"- mock_dt.datetime.now.return_value = mock_now-- result = _get_current_hour_bucket()- assert result == "2024-01-15:14"-- # Test hour 15 (odd) -> bucket starts at 14- mock_now.hour = 15- mock_now.strftime.return_value = "2024-01-15:14"-- result = _get_current_hour_bucket()- assert result == "2024-01-15:14"-- mock_dt.datetime.now.assert_called_with(mock_dt.UTC)-- @patch("posthog.temporal.messaging.quantiles_storage.get_client")- def test_store_quantiles_success(self, mock_get_client):- """Test successful quantile storage."""- mock_redis = Mock()- mock_redis.set.return_value = True # Lock acquired- mock_redis.exists.return_value = False # No existing cache- mock_get_client.return_value = mock_redis-- quantiles = [100.0, 200.0, 300.0]- result = store_quantiles(quantiles, max_value=400, hour_bucket="2024-01-15:14")-- assert result is True- mock_redis.set.assert_called_once() # Lock- mock_redis.setex.assert_called_once() # Store data- # Lock release uses an atomic Lua compare-and-delete via redis_client.eval- mock_redis.eval.assert_called_once()- # Persisted payload is the new dict format including max_value- stored_payload = json.loads(mock_redis.setex.call_args.args[2])- assert stored_payload == {"quantiles": quantiles, "max_value": 400}-- @patch("posthog.temporal.messaging.quantiles_storage.get_client")- def test_store_quantiles_lock_contention(self, mock_get_client):- """Test behavior when lock is already held."""- mock_redis = Mock()- mock_redis.set.return_value = False # Lock not acquired- mock_get_client.return_value = mock_redis-- quantiles = [100.0, 200.0, 300.0]- result = store_quantiles(quantiles, max_value=400, hour_bucket="2024-01-15:14")-- assert result is False- mock_redis.setex.assert_not_called() # Should not store-- @patch("posthog.temporal.messaging.quantiles_storage.get_client")- def test_get_quantiles_hit(self, mock_get_client):- """Test successful cache retrieval."""- mock_redis = Mock()- cached_data = json.dumps({"quantiles": [100.0, 200.0, 300.0], "max_value": 400})- mock_redis.get.return_value = cached_data- mock_get_client.return_value = mock_redis-- result = get_quantiles("2024-01-15:14")-- assert result == CachedQuantiles(quantiles=[100.0, 200.0, 300.0], max_value=400)-- @patch("posthog.temporal.messaging.quantiles_storage.get_client")- def test_get_quantiles_miss(self, mock_get_client):- """Test cache miss."""- mock_redis = Mock()- mock_redis.get.return_value = None- mock_get_client.return_value = mock_redis-- result = get_quantiles("2024-01-15:14")-- assert result is None-- @patch("posthog.temporal.messaging.quantiles_storage.get_client")- def test_get_quantiles_legacy_format_is_treated_as_miss(self, mock_get_client):- """Legacy bare-list cache entries should be discarded so callers recalculate- with the new max_value contract instead of silently mixing formats."""- mock_redis = Mock()- mock_redis.get.return_value = json.dumps([100.0, 200.0, 300.0])- mock_get_client.return_value = mock_redis-- result = get_quantiles("2024-01-15:14")-- assert result is None- mock_redis.delete.assert_called_once()-- @patch("posthog.temporal.messaging.quantiles_storage.get_client")- @patch("posthog.temporal.messaging.quantiles_storage.time.sleep")- def test_get_or_calculate_race_condition_handling(self, mock_sleep, mock_get_client):- """Test race condition handling with retry logic."""- mock_redis = Mock()- mock_get_client.return_value = mock_redis-- with patch("statistics.quantiles", return_value=[100.0, 200.0, 300.0]):- cached_payload = json.dumps({"quantiles": [100.0, 200.0, 300.0], "max_value": 250})- # First call: cache miss for current bucket- # Second call: cache miss for previous bucket- # Third call: lock contention, then cache hit after retry- mock_redis.get.side_effect = [- None, # Initial cache miss (current hour)- None, # Previous hour cache miss- None, # Still miss after first store attempt fails- cached_payload, # Hit after retry- ]- mock_redis.set.side_effect = [False, True] # First lock fails, second succeeds- mock_redis.exists.return_value = False-- durations = [50, 100, 150, 200, 250]- result = get_cached_quantiles_or_calculate(durations, "2024-01-15:14", max_retries=2)-- assert result == CachedQuantiles(quantiles=[100.0, 200.0, 300.0], max_value=250)- assert mock_sleep.call_count == 1 # Should retry once-- def test_race_condition_scenario_realistic(self):- """Test realistic race condition scenario with multiple workflows."""- # This test simulates what happens when p0-p50 and p50-p80 workflows- # start at the same time and both try to calculate quantiles-- durations = list(range(100, 1000, 10)) # Realistic duration spread- cached_payload = json.dumps({"quantiles": [200.0, 400.0, 600.0], "max_value": 990})-- with patch("posthog.temporal.messaging.quantiles_storage.get_client") as mock_get_client:- mock_redis = Mock()- mock_get_client.return_value = mock_redis- mock_redis.exists.return_value = False- # Workflow 1: both current and previous-hour buckets miss → calculates and stores;- # Workflow 2: current-hour bucket hits the populated cache.- mock_redis.get.side_effect = [- None, # workflow 1: current bucket miss- None, # workflow 1: previous-hour fallback miss- cached_payload, # workflow 2: current bucket hit- ]- mock_redis.set.side_effect = [True] # workflow 1 acquires lock-- # First workflow calculates and stores- result1 = get_cached_quantiles_or_calculate(durations, "2024-01-15:14")-- # Second workflow gets from cache- result2 = get_cached_quantiles_or_calculate(durations, "2024-01-15:14")-- # Both should be populated; workflow 2's result is the canonical cached value- assert result1 is not None- assert result2 == CachedQuantiles(quantiles=[200.0, 400.0, 600.0], max_value=990)diff --git a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.pydeleted file mode 100644index 5eba6bd1cf2b..000000000000--- a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py+++ /dev/null@@ -1,1825 +0,0 @@-import os-from types import TracebackType--import pytest-from unittest.mock import AsyncMock, Mock, patch--from posthog.temporal.messaging.realtime_cohort_calculation_workflow import (- RealtimeCohortCalculationWorkflowInputs,- _batch_update_cohort_metrics,- build_final_query,- flush_kafka_batch,- process_realtime_cohort_calculation_activity,-)-from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- CohortSelectionActivityInput,- QueryPercentileThresholds,- QueryPercentileThresholdsInput,- RealtimeCohortCalculationCoordinatorWorkflowInputs,- _apply_duration_filtering,- get_query_percentile_thresholds_activity,- get_realtime_cohort_selection_activity,-)---class TestFlushKafkaBatch:- """Tests for the flush_kafka_batch helper function."""-- @pytest.mark.asyncio- async def test_empty_messages_returns_zero(self):- """When pending_messages is empty, should return 0 without flushing."""- kafka_producer = Mock()- heartbeater = Mock()- logger = Mock()-- result = await flush_kafka_batch(- kafka_producer=kafka_producer,- pending_messages=[],- cohort_id=123,- idx=1,- total_cohorts=5,- heartbeater=heartbeater,- logger=logger,- percentile_bucket="p0-p50",- )-- assert result == 0- kafka_producer.flush.assert_not_called()-- @pytest.mark.asyncio- async def test_successful_batch_flush(self):- """Should flush messages and return batch size on success."""- kafka_producer = Mock()- kafka_producer.flush = Mock()-- # Mock successful send results- mock_results = [Mock() for _ in range(100)]- for mock_result in mock_results:- mock_result.get = Mock(return_value=None)-- heartbeater = Mock()- logger = Mock()-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow.asyncio.to_thread") as mock_thread:- mock_thread.return_value = None-- result = await flush_kafka_batch(- kafka_producer=kafka_producer,- pending_messages=mock_results,- cohort_id=123,- idx=1,- total_cohorts=5,- heartbeater=heartbeater,- logger=logger,- percentile_bucket="p0-p50",- )-- assert result == 100- mock_thread.assert_called_once_with(kafka_producer.flush)- logger.info.assert_called_once()-- @pytest.mark.asyncio- async def test_final_batch_includes_final_in_messages(self):- """When is_final=True, should include 'final' in heartbeat and log messages."""- kafka_producer = Mock()- mock_result = Mock()- mock_result.get = Mock(return_value=None)-- heartbeater = Mock()- logger = Mock()-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow.asyncio.to_thread"):- await flush_kafka_batch(- kafka_producer=kafka_producer,- pending_messages=[mock_result],- cohort_id=123,- idx=1,- total_cohorts=5,- heartbeater=heartbeater,- logger=logger,- percentile_bucket="p0-p50",- is_final=True,- )-- # Check heartbeat details includes "final"- assert heartbeater.details[0].startswith("Flushing final ")-- # Check logger includes "final"- log_call_args = logger.info.call_args[0][0]- assert "final" in log_call_args.lower()-- @pytest.mark.asyncio- async def test_non_final_batch_excludes_final_from_messages(self):- """When is_final=False, should not include 'final' in messages."""- kafka_producer = Mock()- mock_result = Mock()- mock_result.get = Mock(return_value=None)-- heartbeater = Mock()- logger = Mock()-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow.asyncio.to_thread"):- await flush_kafka_batch(- kafka_producer=kafka_producer,- pending_messages=[mock_result],- cohort_id=123,- idx=1,- total_cohorts=5,- heartbeater=heartbeater,- logger=logger,- percentile_bucket="p0-p50",- is_final=False,- )-- # Check heartbeat details does not include "final"- heartbeat_msg = heartbeater.details[0]- assert "final" not in heartbeat_msg.lower()-- # Check logger does not include "final"- log_call_args = logger.info.call_args[0][0]- assert "final" not in log_call_args.lower()-- @pytest.mark.asyncio- async def test_batch_flush_with_partial_failures(self):- """Should raise exception when some messages fail to send."""- kafka_producer = Mock()-- # Create mix of successful and failed results- successful_result = Mock()- successful_result.get = Mock(return_value=None)-- failed_result = Mock()- failed_result.get = Mock(side_effect=Exception("Send failed"))-- mock_results = [successful_result, failed_result, successful_result]-- heartbeater = Mock()- logger = Mock()-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow.asyncio.to_thread"):- with pytest.raises(Exception, match="Failed to send 1/3 Kafka messages"):- await flush_kafka_batch(- kafka_producer=kafka_producer,- pending_messages=mock_results,- cohort_id=123,- idx=1,- total_cohorts=5,- heartbeater=heartbeater,- logger=logger,- percentile_bucket="p0-p50",- )-- # Should log warnings for failed messages- assert logger.warning.call_count == 1- # Should log error summary- assert logger.error.call_count == 1-- @pytest.mark.asyncio- async def test_batch_flush_with_all_failures(self):- """Should raise exception when all messages fail to send."""- kafka_producer = Mock()-- # All results fail- mock_results = []- for _ in range(5):- failed_result = Mock()- failed_result.get = Mock(side_effect=Exception("Send failed"))- mock_results.append(failed_result)-- heartbeater = Mock()- logger = Mock()-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow.asyncio.to_thread"):- with pytest.raises(Exception, match="Failed to send 5/5 Kafka messages"):- await flush_kafka_batch(- kafka_producer=kafka_producer,- pending_messages=mock_results,- cohort_id=123,- idx=1,- total_cohorts=5,- heartbeater=heartbeater,- logger=logger,- percentile_bucket="p0-p50",- )-- assert logger.warning.call_count == 5- assert logger.error.call_count == 1-- @pytest.mark.asyncio- async def test_heartbeat_details_format(self):- """Should format heartbeat details with cohort progress information."""- kafka_producer = Mock()- mock_result = Mock()- mock_result.get = Mock(return_value=None)-- heartbeater = Mock()- logger = Mock()-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow.asyncio.to_thread"):- await flush_kafka_batch(- kafka_producer=kafka_producer,- pending_messages=[mock_result] * 10000,- cohort_id=456,- idx=3,- total_cohorts=10,- heartbeater=heartbeater,- logger=logger,- percentile_bucket="p50-p80",- )-- heartbeat_msg = heartbeater.details[0]- assert "10000 messages" in heartbeat_msg- assert "cohort 3/10" in heartbeat_msg- assert "cohort_id=456" in heartbeat_msg-- @pytest.mark.asyncio- async def test_logger_includes_cohort_metadata(self):- """Should include cohort_id and batch_size in logger metadata."""- kafka_producer = Mock()- mock_result = Mock()- mock_result.get = Mock(return_value=None)-- heartbeater = Mock()- logger = Mock()-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow.asyncio.to_thread"):- await flush_kafka_batch(- kafka_producer=kafka_producer,- pending_messages=[mock_result] * 5000,- cohort_id=789,- idx=2,- total_cohorts=8,- heartbeater=heartbeater,- logger=logger,- percentile_bucket="p80-p90",- )-- # Check logger.info was called with metadata- logger.info.assert_called_once()- call_kwargs = logger.info.call_args[1]- assert call_kwargs["cohort_id"] == 789- assert call_kwargs["batch_size"] == 5000---class TestBatchFlushingBehavior:- """Tests for batch flushing logic and integration."""-- def test_flush_batch_size_env_var_configuration(self):- """Verify FLUSH_BATCH_SIZE uses environment variable configuration."""- # Test default value (1000 when env var is not set)- with patch.dict(os.environ, {}, clear=True):- # Test the env parsing logic directly- default_value = int(os.environ.get("COHORT_KAFKA_FLUSH_BATCH_SIZE", "1000"))- assert default_value == 1000-- # Test env var override- with patch.dict(os.environ, {"COHORT_KAFKA_FLUSH_BATCH_SIZE": "500"}):- env_value = int(os.environ.get("COHORT_KAFKA_FLUSH_BATCH_SIZE", "1000"))- assert env_value == 500-- # Test that the module constant exists and is configurable- import posthog.temporal.messaging.realtime_cohort_calculation_workflow as module-- assert hasattr(module, "FLUSH_BATCH_SIZE")- assert isinstance(module.FLUSH_BATCH_SIZE, int)-- @pytest.mark.asyncio- async def test_multiple_batches_handled_correctly(self):- """Should handle multiple batch flushes correctly."""- kafka_producer = Mock()-- # Simulate 3 batches: 10k, 10k, 5k- heartbeater = Mock()- logger = Mock()-- mock_results_batch1 = [Mock() for _ in range(10000)]- mock_results_batch2 = [Mock() for _ in range(10000)]- mock_results_batch3 = [Mock() for _ in range(5000)]-- for result in mock_results_batch1 + mock_results_batch2 + mock_results_batch3:- result.get = Mock(return_value=None)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow.asyncio.to_thread"):- # Batch 1- result1 = await flush_kafka_batch(- kafka_producer, mock_results_batch1, 123, 1, 5, heartbeater, logger, "p90-p95"- )- # Batch 2- result2 = await flush_kafka_batch(- kafka_producer, mock_results_batch2, 123, 1, 5, heartbeater, logger, "p90-p95"- )- # Batch 3 (final)- result3 = await flush_kafka_batch(- kafka_producer, mock_results_batch3, 123, 1, 5, heartbeater, logger, "p90-p95", is_final=True- )-- assert result1 == 10000- assert result2 == 10000- assert result3 == 5000- assert result1 + result2 + result3 == 25000---class TestRealtimeCohortCalculationCoordinator:- """Tests for the coordinator workflow and percentage-based cohort selection."""-- def test_coordinator_workflow_inputs_includes_team_ids(self):- """RealtimeCohortCalculationCoordinatorWorkflowInputs should include team_ids and global_percentage."""- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- parallelism=5,- workflows_per_batch=2,- batch_delay_minutes=3,- cohort_id=None,- team_ids={2, 42},- global_percentage=0.5,- )-- assert inputs.team_ids == {2, 42}- assert inputs.global_percentage == 0.5-- # Check it's included in properties_to_log- props = inputs.properties_to_log- assert "team_ids" in props- assert "global_percentage" in props- assert set(props["team_ids"]) == {2, 42}- assert props["global_percentage"] == 0.5-- def test_coordinator_workflow_inputs_with_simple_structure(self):- """RealtimeCohortCalculationCoordinatorWorkflowInputs should support simple team_ids + global_percentage structure."""- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- parallelism=5,- workflows_per_batch=2,- batch_delay_minutes=3,- cohort_id=None,- team_ids={42, 100},- global_percentage=0.3,- )-- assert inputs.team_ids == {42, 100}- assert inputs.global_percentage == 0.3-- # Check it's included in properties_to_log- props = inputs.properties_to_log- assert "team_ids" in props- assert "global_percentage" in props- assert set(props["team_ids"]) == {42, 100}- assert props["global_percentage"] == 0.3-- def test_coordinator_workflow_inputs_preserves_none_values(self):- """Should preserve None values for deterministic Temporal workflow behavior."""- # __post_init__ was removed to ensure Temporal workflow determinism- # Django settings are now loaded at schedule creation time, not during deserialization- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs()-- # Should preserve explicit None values instead of auto-loading from settings- assert inputs.team_ids is None- assert inputs.global_percentage is None-- def test_coordinator_workflow_inputs_explicit_values(self):- """Should preserve explicit values without auto-loading from settings."""- # __post_init__ was removed to ensure Temporal workflow determinism- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids=set(), # Explicitly empty (not None)- global_percentage=None, # Explicitly None- )-- # Should preserve user's explicit values without loading from Django settings- assert inputs.team_ids == set() # User's explicit empty set- assert inputs.global_percentage is None # User's explicit None-- def test_parse_inputs_loads_django_settings(self):- """Should load Django settings when using parse_inputs for CLI usage."""- from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- RealtimeCohortCalculationCoordinatorWorkflow,- )-- with (- patch("posthog.settings.schedules.REALTIME_COHORT_CALCULATION_TEAMS", {42, 100}),- patch("posthog.settings.schedules.REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE", 0.75),- ):- # parse_inputs should load Django settings for CLI usage- inputs = RealtimeCohortCalculationCoordinatorWorkflow.parse_inputs([])-- # Should load settings values for CLI usage- assert inputs.team_ids == {42, 100}- assert inputs.global_percentage == 0.75-- def test_team_percentages_parsing_from_env_var(self):- """Test parsing team percentages from environment variable using JSON format."""- import json-- # Test the JSON parsing directly with mock env var values- with patch("posthog.settings.schedules.get_from_env") as mock_get_env:- # Test simple single team format- mock_get_env.return_value = '{"2": 0.5}'- raw_settings = json.loads(mock_get_env.return_value)- result = {int(k): float(v) for k, v in raw_settings.items()}- assert result == {2: 0.5}-- # Test multiple teams format- mock_get_env.return_value = '{"2": 0.3, "42": 0.8}'- raw_settings = json.loads(mock_get_env.return_value)- result = {int(k): float(v) for k, v in raw_settings.items()}- assert result == {2: 0.3, 42: 0.8}-- def test_team_percentages_parsing_with_invalid_format(self):- """Test parsing handles invalid JSON gracefully by falling back to default."""- import json-- with patch("posthog.settings.schedules.get_from_env") as mock_get_env:- # Test invalid JSON format - should fall back to default- mock_get_env.return_value = "invalid json"- try:- raw_settings = json.loads(mock_get_env.return_value)- result = {int(k): float(v) for k, v in raw_settings.items()}- except Exception:- result = {2: 0.0} # Fallback to default-- # Should use the fallback default- assert result == {2: 0.0}-- def test_worker_inputs_support_cohort_id_array(self):- """Worker inputs should support receiving cohort ID arrays from coordinator."""-- from posthog.temporal.messaging.realtime_cohort_calculation_workflow import (- RealtimeCohortCalculationWorkflowInputs,- )-- # Test new array approach- inputs = RealtimeCohortCalculationWorkflowInputs(cohort_ids=[10, 15, 20, 25])-- assert inputs.cohort_ids == [10, 15, 20, 25]- assert inputs.properties_to_log["cohort_ids"] == [10, 15, 20, 25]- assert inputs.properties_to_log["num_cohorts"] == 4-- # Test array approach with many cohorts (should truncate in logs)- many_cohort_ids = list(range(1, 16)) # 1-15- inputs_many = RealtimeCohortCalculationWorkflowInputs(cohort_ids=many_cohort_ids)-- assert inputs_many.cohort_ids == many_cohort_ids- assert inputs_many.properties_to_log["cohort_ids"] == list(range(1, 11)) # First 10- assert inputs_many.properties_to_log["num_cohorts"] == 15-- # Test backward compatibility with single cohort_id- inputs_single = RealtimeCohortCalculationWorkflowInputs(cohort_id=42)-- assert inputs_single.cohort_id == 42- assert inputs_single.cohort_ids is None- assert inputs_single.properties_to_log["cohort_id"] == 42- assert inputs_single.properties_to_log["num_cohorts"] == 1-- # Test empty case- inputs_empty = RealtimeCohortCalculationWorkflowInputs()-- assert inputs_empty.cohort_ids is None- assert inputs_empty.cohort_id is None- assert inputs_empty.properties_to_log["num_cohorts"] == 0---class TestRealtimeCohortSelectionActivity:- """Tests for the get_realtime_cohort_selection_activity function."""-- @pytest.mark.asyncio- async def test_selection_activity_with_specific_cohort_id_exists(self):- """When cohort_id is specified and exists, should return that cohort ID."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(cohort_id=123)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.exists.return_value = True- mock_cohort.objects.filter.return_value = mock_queryset-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- assert result.cohort_ids == [123]- mock_cohort.objects.filter.assert_called_once()-- @pytest.mark.asyncio- async def test_selection_activity_with_specific_cohort_id_not_exists(self):- """When cohort_id is specified but doesn't exist, should return empty list."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(cohort_id=999)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.exists.return_value = False- mock_cohort.objects.filter.return_value = mock_queryset-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- assert result.cohort_ids == []-- @pytest.mark.asyncio- async def test_selection_activity_with_team_ids_only(self):- """Should select all cohorts for specified teams."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(team_ids={2, 3}, global_percentage=None)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Combined teams query returns all cohorts from teams 2 and 3- combined_teams_queryset = Mock()- combined_teams_queryset.order_by.return_value.values_list.return_value = [10, 20, 30, 40]-- mock_cohort.objects.filter.return_value = combined_teams_queryset-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- # Should include all cohorts from both teams, sorted by duration then ID- assert result.cohort_ids == [10, 20, 30, 40]-- # Verify ordering is applied with F expression and nulls_last- from django.db.models import F-- combined_teams_queryset.order_by.assert_called_once_with(- F("last_calculation_duration_ms").asc(nulls_last=True), "id"- )-- @pytest.mark.asyncio- async def test_selection_activity_with_global_percentage_only(self):- """Should select percentage of all cohorts when no teams specified."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids=set(),- global_percentage=0.5, # 50%- )-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # All teams have cohorts [1, 2, 3, 4, 5, 6] ordered by duration (shortest first, nulls last)- queryset = Mock()- queryset.order_by.return_value.values_list.return_value = [1, 2, 3, 4, 5, 6]- mock_cohort.objects.filter.return_value = queryset-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- # Should select 50% = 3 cohorts (random sampling, but always 3 total)- assert len(result.cohort_ids) == 3- # All selected IDs should be from the available set- assert all(cohort_id in [1, 2, 3, 4, 5, 6] for cohort_id in result.cohort_ids)- # Should be unique- assert len(set(result.cohort_ids)) == 3-- # Verify ordering is applied with F expression and nulls_last- from django.db.models import F-- queryset.order_by.assert_called_once_with(F("last_calculation_duration_ms").asc(nulls_last=True), "id")-- @pytest.mark.asyncio- async def test_selection_activity_with_small_global_percentage_returns_zero(self):- """Should return empty list when global percentage results in zero cohorts."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids=set(),- global_percentage=0.01, # 1% of 10 = 0.1 → 0- )-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- queryset = Mock()- queryset.order_by.return_value.values_list.return_value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]- mock_cohort.objects.filter.return_value = queryset-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- # Should be empty since int(10 * 0.01) = 0- assert result.cohort_ids == []-- @pytest.mark.asyncio- async def test_selection_activity_with_team_ids_and_global_percentage(self):- """Should combine team-specific cohorts with global percentage of other teams."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids={2},- global_percentage=0.5, # 50% of other teams- )-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Team 2 has cohorts [10, 20]- team2_queryset = Mock()- team2_queryset.order_by.return_value.values_list.return_value = [10, 20]-- # Other teams (excluding team 2) have cohorts [1, 2, 3, 4]- other_teams_base_queryset = Mock()- other_teams_queryset = Mock()- other_teams_queryset.order_by.return_value.values_list.return_value = [1, 2, 3, 4]- other_teams_base_queryset.exclude.return_value = other_teams_queryset-- mock_cohort.objects.filter.side_effect = [team2_queryset, other_teams_base_queryset]-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- # Should include:- # - All cohorts from team 2: [10, 20]- # - 50% of other teams: 2 out of [1, 2, 3, 4] (random selection)- assert len(result.cohort_ids) == 4- # Must include all team 2 cohorts- assert 10 in result.cohort_ids- assert 20 in result.cohort_ids- # Must include exactly 2 from other teams- other_team_cohorts = [id for id in result.cohort_ids if id in [1, 2, 3, 4]]- assert len(other_team_cohorts) == 2-- @pytest.mark.asyncio- async def test_selection_activity_deduplication(self):- """Should remove duplicate cohort IDs while preserving order."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(team_ids={2, 3}, global_percentage=0.5)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Combined teams query returns all cohorts from teams 2 and 3- # Team 2: [10, 30], Team 3: [20, 30] -> Combined: [10, 30, 20, 30]- combined_teams_queryset = Mock()- combined_teams_queryset.order_by.return_value.values_list.return_value = [10, 30, 20, 30]-- # Other teams have cohorts [1, 2, 10] - note: 10 is duplicate- other_teams_base_queryset = Mock()- other_teams_queryset = Mock()- other_teams_queryset.order_by.return_value.values_list.return_value = [1, 2, 10]- other_teams_base_queryset.exclude.return_value = other_teams_queryset-- mock_cohort.objects.filter.side_effect = [combined_teams_queryset, other_teams_base_queryset]-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- # Should include forced teams cohorts: [10, 30, 20]- # Plus 50% of other teams' [1, 2, 10] = 1 cohort (random sampling)- # After deduplication: depends on which cohort was randomly selected-- # Should always include all forced team cohorts- assert all(cohort_id in result.cohort_ids for cohort_id in [10, 20, 30])-- # Check what was randomly selected from other teams- other_cohorts = [id for id in result.cohort_ids if id not in [10, 20, 30]]-- if len(other_cohorts) == 1:- # Selected a unique cohort (1 or 2)- assert len(result.cohort_ids) == 4- assert other_cohorts[0] in [1, 2]- else:- # Selected cohort 10 (duplicate), so deduplicated to 3 total- assert len(result.cohort_ids) == 3- assert len(other_cohorts) == 0-- # Should contain the expected cohorts (order is preserved from DB queries + random sampling)- assert set(result.cohort_ids) == {10, 20, 30, *other_cohorts}-- @pytest.mark.asyncio- async def test_selection_activity_skips_invalid_team_ids(self):- """Should skip invalid team IDs (non-int or <= 0)."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids={2, 0, -1}, # 0 and -1 are invalid- global_percentage=None,- )-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Only team 2 should be queried- team2_queryset = Mock()- team2_queryset.order_by.return_value.values_list.return_value = [10, 20]- mock_cohort.objects.filter.return_value = team2_queryset-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- # Should only include cohorts from team 2- assert result.cohort_ids == [10, 20]- # Should only call filter once (for valid team 2)- assert mock_cohort.objects.filter.call_count == 1-- @pytest.mark.asyncio- async def test_selection_activity_random_sampling(self):- """Should select cohorts using random sampling for fair distribution over time."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(team_ids=set(), global_percentage=0.6)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Cohorts returned in different order from DB- queryset = Mock()- queryset.order_by.return_value.values_list.return_value = [50, 10, 30, 20, 40]- mock_cohort.objects.filter.return_value = queryset-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- # Should select 60% = 3 cohorts, randomly sampled- assert len(result.cohort_ids) == 3- # All selected IDs should be from available set- assert all(cohort_id in [50, 10, 30, 20, 40] for cohort_id in result.cohort_ids)- # Should be unique- assert len(set(result.cohort_ids)) == 3- # Order is preserved from random sampling (not sorted)- assert len(result.cohort_ids) == len(set(result.cohort_ids)) # Check uniqueness-- # Verify ordering is applied with F expression and nulls_last- from django.db.models import F-- queryset.order_by.assert_called_once_with(F("last_calculation_duration_ms").asc(nulls_last=True), "id")-- @pytest.mark.asyncio- async def test_selection_activity_random_variability(self):- """Should select different cohorts on different runs due to randomness."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(team_ids=set(), global_percentage=0.5)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Set up cohorts- queryset = Mock()- queryset.order_by.return_value.values_list.return_value = [1, 2, 3, 4, 5, 6]- mock_cohort.objects.filter.return_value = queryset-- # Run multiple times to verify randomness- results = []- for _ in range(10): # Run 10 times to get some variability- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)- results.append(set(result.cohort_ids))-- # All should select 50% = 3 cohorts- assert all(len(result) == 3 for result in results)-- # With random sampling, we should see some variability in selections- # (It's theoretically possible all runs select the same cohorts, but extremely unlikely)- unique_selections = {frozenset(result) for result in results}- assert len(unique_selections) > 1, "Random sampling should produce different selections"-- @pytest.mark.asyncio- async def test_selection_activity_respects_duration_ordering_with_nulls(self):- """Should verify that ordering respects last_calculation_duration_ms with NULLs last."""-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(team_ids={1}, global_percentage=None)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Mock queryset that simulates proper duration-based ordering- # In practice, this would return cohorts ordered by duration: shortest first, NULLs last- queryset = Mock()- # Cohorts returned in proper duration order (e.g., 1000ms, 2000ms, 5000ms, then NULL durations)- queryset.order_by.return_value.values_list.return_value = [10, 20, 30, 40, 50]- mock_cohort.objects.filter.return_value = queryset-- activity_input = CohortSelectionActivityInput(coordinator_inputs=inputs)- result = await get_realtime_cohort_selection_activity(activity_input)-- # Should maintain the duration-based ordering from the queryset- assert result.cohort_ids == [10, 20, 30, 40, 50]-- # Most importantly, verify the F expression with nulls_last is used- from django.db.models import F-- queryset.order_by.assert_called_once_with(F("last_calculation_duration_ms").asc(nulls_last=True), "id")---class TestDurationFiltering:- """Tests for duration-based cohort filtering functionality."""-- def test_apply_duration_filtering_no_thresholds(self):- """Should return original queryset when no thresholds provided."""- mock_queryset = Mock()-- result = _apply_duration_filtering(mock_queryset, None)-- assert result is mock_queryset- # Should not call any filter methods- assert not mock_queryset.filter.called-- def test_apply_duration_filtering_normal_range(self):- """Should apply both lower and upper bounds for normal percentile ranges."""- mock_queryset = Mock()- mock_filtered_queryset = Mock()- mock_queryset.filter.return_value = mock_filtered_queryset-- thresholds = QueryPercentileThresholds(- min_threshold_ms=5000, # 5 seconds- max_threshold_ms=30000, # 30 seconds- )-- result = _apply_duration_filtering(mock_queryset, thresholds, is_p100=False)-- assert result is mock_filtered_queryset- mock_queryset.filter.assert_called_once_with(- last_calculation_duration_ms__gte=5000, # 5s * 1000- last_calculation_duration_ms__lt=30000, # 30s * 1000- )-- def test_apply_duration_filtering_p100_includes_nulls(self):- """Should include NULL durations when filtering p100 range (slowest tier)."""- from django.db.models import Q-- mock_queryset = Mock()- mock_filtered_queryset = Mock()- mock_queryset.filter.return_value = mock_filtered_queryset-- thresholds = QueryPercentileThresholds(- min_threshold_ms=60000, # 60 seconds minimum- max_threshold_ms=120000, # This value doesn't matter for p100- )-- result = _apply_duration_filtering(mock_queryset, thresholds, is_p100=True)-- assert result is mock_filtered_queryset- # Should use Q objects to include both duration >= threshold OR NULL- mock_queryset.filter.assert_called_once()- filter_args = mock_queryset.filter.call_args[0]- assert len(filter_args) == 1- q_filter = filter_args[0]- assert isinstance(q_filter, Q)-- def test_apply_duration_filtering_p100_vs_normal(self):- """Should behave differently for p100 vs normal ranges with same thresholds."""- mock_queryset = Mock()- thresholds = QueryPercentileThresholds(min_threshold_ms=10, max_threshold_ms=50)-- # Normal range (p90-p95)- _apply_duration_filtering(mock_queryset, thresholds, is_p100=False)- normal_call = mock_queryset.filter.call_args-- mock_queryset.reset_mock()-- # P100 range (p99-p100)- _apply_duration_filtering(mock_queryset, thresholds, is_p100=True)- p100_call = mock_queryset.filter.call_args-- # Should use different filtering logic- assert normal_call != p100_call-- def test_apply_duration_filtering_uses_millisecond_values(self):- """Should use millisecond threshold values directly in filtering."""- mock_queryset = Mock()-- thresholds = QueryPercentileThresholds(- min_threshold_ms=2500, # 2.5 seconds in milliseconds- max_threshold_ms=7250, # 7.25 seconds in milliseconds- )-- _apply_duration_filtering(mock_queryset, thresholds, is_p100=False)-- mock_queryset.filter.assert_called_once_with(- last_calculation_duration_ms__gte=2500,- last_calculation_duration_ms__lt=7250,- )-- def test_apply_duration_filtering_identical_thresholds(self):- """Should use __lte instead of __lt when min and max thresholds are identical.-- This handles the edge case where all cohorts have identical durations,- causing quantile boundaries to be the same value. Using __lt would match- zero rows, but __lte correctly matches cohorts at that exact duration.- """- mock_queryset = Mock()- mock_filtered_queryset = Mock()- mock_queryset.filter.return_value = mock_filtered_queryset-- # Identical thresholds simulate the case where all cohorts have the same duration- thresholds = QueryPercentileThresholds(- min_threshold_ms=5000, # Same value- max_threshold_ms=5000, # Same value- )-- result = _apply_duration_filtering(mock_queryset, thresholds, is_p100=False)-- assert result is mock_filtered_queryset- # Should use __lte instead of __lt when thresholds are identical- mock_queryset.filter.assert_called_once_with(- last_calculation_duration_ms__gte=5000,- last_calculation_duration_ms__lte=5000, # __lte instead of __lt- )---class TestQueryPercentileThresholdsActivity:- """Tests for ClickHouse percentile threshold calculation."""-- @pytest.mark.asyncio- @pytest.mark.django_db- async def test_get_percentile_thresholds_success(self):- """Should successfully calculate percentile thresholds from cohort data."""- inputs = QueryPercentileThresholdsInput(- min_percentile=90.0, # p90- max_percentile=95.0, # p95- )-- # Mock cohort queryset with duration data (in milliseconds)- mock_durations = [- 1000,- 2000,- 3000,- 4000,- 5000,- 6000,- 7000,- 8000,- 9000,- 10000,- 11000,- 12000,- 13000,- 14000,- 15000,- 16000,- 17000,- 18000,- 19000,- 20000,- ]-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Create a mock values_list queryset that behaves like an actual queryset- mock_values_list_qs = Mock()- mock_values_list_qs.__bool__ = Mock(return_value=True) # Make it truthy for the `if not` check- mock_values_list_qs.__iter__ = Mock(return_value=iter(mock_durations)) # Make it iterable- mock_values_list_qs.__len__ = Mock(return_value=len(mock_durations)) # Support len()-- # Create a filter queryset that returns the values_list queryset- mock_filter_qs = Mock()- mock_filter_qs.values_list.return_value = mock_values_list_qs-- mock_cohort.objects.filter.return_value = mock_filter_qs-- result = await get_query_percentile_thresholds_activity(inputs)-- assert result is not None- # With 20 data points, p90 should be around 18000ms, p95 around 19000ms- assert result.min_threshold_ms >= 17000- assert result.min_threshold_ms <= 19000- assert result.max_threshold_ms >= 18000- assert result.max_threshold_ms <= 20000-- @pytest.mark.asyncio- async def test_get_percentile_thresholds_defaults_to_p0_p100(self):- """Should default to p0-p100 when percentiles not specified."""- from posthog.temporal.messaging.quantiles_storage import CachedQuantiles-- inputs = QueryPercentileThresholdsInput() # No percentiles specified-- # Mock cohort queryset with duration data (in milliseconds)- mock_durations = [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000]-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = mock_durations- mock_cohort.objects.filter.return_value = mock_queryset-- # Pin the cache lookup so the test isn't affected by Redis state from- # previous tests in the session.- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",- return_value=CachedQuantiles(quantiles=[float(d) for d in mock_durations] * 10, max_value=5000),- ):- result = await get_query_percentile_thresholds_activity(inputs)-- assert result is not None- # p0 is treated as a lower bound of 0, p100 should be the cached max value (5000)- assert result.min_threshold_ms == 0 # p0 (lower bound)- assert result.max_threshold_ms == 5000 # p100 (cached max)-- @pytest.mark.asyncio- @pytest.mark.django_db- async def test_get_percentile_thresholds_no_historical_data(self):- """Should return None when no historical cohort data exists."""- inputs = QueryPercentileThresholdsInput(min_percentile=0.0, max_percentile=90.0)-- # Empty result from Cohort queryset (no historical durations)- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = []- mock_cohort.objects.filter.return_value = mock_queryset-- result = await get_query_percentile_thresholds_activity(inputs)-- assert result is None-- @pytest.mark.asyncio- @pytest.mark.django_db- async def test_get_percentile_thresholds_insufficient_data(self):- """Should return None when Cohort data has insufficient data points."""- inputs = QueryPercentileThresholdsInput(min_percentile=50.0, max_percentile=75.0)-- # Only one data point (need at least 2 for meaningful percentiles)- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = [1000]- mock_cohort.objects.filter.return_value = mock_queryset-- # Patch the imported reference (not the source module) and force a cache miss- # so the activity falls through to the insufficient-data check inside- # get_cached_quantiles_or_calculate.- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",- return_value=None,- ):- result = await get_query_percentile_thresholds_activity(inputs)-- assert result is None-- @pytest.mark.asyncio- @pytest.mark.django_db- async def test_get_percentile_thresholds_statistics_error(self):- """Should return None when quantiles calculation fails."""- inputs = QueryPercentileThresholdsInput(min_percentile=75.0, max_percentile=90.0)-- # Mock data that will cause statistics error (too few points for percentile calculation)- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = [100, 200] # Valid data- mock_cohort.objects.filter.return_value = mock_queryset-- # Mock the quantiles cache to return None (indicating calculation failure)- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",- return_value=None,- ):- result = await get_query_percentile_thresholds_activity(inputs)-- assert result is None-- @pytest.mark.asyncio- @pytest.mark.django_db- async def test_get_percentile_thresholds_invalid_data_types(self):- """Should return None when quantiles calculation fails due to invalid data."""- inputs = QueryPercentileThresholdsInput(min_percentile=80.0, max_percentile=95.0)-- # Invalid duration data format (non-numeric values)- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = ["invalid-duration", "another-invalid"]- mock_cohort.objects.filter.return_value = mock_queryset-- # Mock the quantiles cache to return None (indicating calculation failure due to invalid data)- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",- return_value=None,- ):- result = await get_query_percentile_thresholds_activity(inputs)-- assert result is None-- @pytest.mark.asyncio- @pytest.mark.django_db- async def test_get_percentile_thresholds_database_error_propagates(self):- """Should propagate database errors for Temporal retry instead of silently returning None."""- inputs = QueryPercentileThresholdsInput(min_percentile=60.0, max_percentile=80.0)-- # Mock database error- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Simulate database connection error- mock_cohort.objects.filter.side_effect = Exception("Database connection failed")-- # Should propagate the database error instead of returning None- with pytest.raises(Exception, match="Database connection failed"):- await get_query_percentile_thresholds_activity(inputs)-- @pytest.mark.asyncio- @pytest.mark.django_db- async def test_get_percentile_thresholds_django_db_error_propagates(self):- """Should propagate Django database errors for Temporal retry."""- from django.db import OperationalError-- inputs = QueryPercentileThresholdsInput(min_percentile=50.0, max_percentile=90.0)-- # Mock Django database error (connection timeout, etc.)- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- # Simulate Django OperationalError (connection timeout, server unavailable, etc.)- mock_cohort.objects.filter.side_effect = OperationalError("Connection to database lost")-- # Should propagate the database error for Temporal retry- with pytest.raises(OperationalError, match="Connection to database lost"):- await get_query_percentile_thresholds_activity(inputs)-- @pytest.mark.asyncio- @pytest.mark.django_db- async def test_get_percentile_thresholds_type_error(self):- """Should return None when quantiles calculation fails due to type errors."""- inputs = QueryPercentileThresholdsInput(min_percentile=70.0, max_percentile=85.0)-- # Mock data that will cause TypeError during max() operation- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- # Mix of numbers and non-numeric data that will cause TypeError- mock_queryset.values_list.return_value = [100, None, 200, 300]- mock_cohort.objects.filter.return_value = mock_queryset-- # Mock the quantiles cache to return None (indicating calculation failure due to type errors)- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate",- return_value=None,- ):- result = await get_query_percentile_thresholds_activity(inputs)-- assert result is None---class TestDurationFilteringIntegration:- """Integration tests for duration filtering with cohort selection."""-- @pytest.mark.asyncio- async def test_selection_activity_with_duration_thresholds_p90_p95(self):- """Should apply duration filtering for p90-p95 percentile range."""- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids={2}, duration_percentile_min=90.0, duration_percentile_max=95.0- )-- thresholds = QueryPercentileThresholds(- min_threshold_ms=10000, # 10 seconds- max_threshold_ms=25000, # 25 seconds- )-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_initial_queryset = Mock()- mock_filtered_queryset = Mock()- mock_filtered_queryset.order_by.return_value.values_list.return_value = [100, 200]- mock_initial_queryset.filter.return_value = mock_filtered_queryset-- mock_cohort.objects.filter.return_value = mock_initial_queryset-- activity_input = CohortSelectionActivityInput(- coordinator_inputs=inputs, query_percentile_thresholds=thresholds- )- result = await get_realtime_cohort_selection_activity(activity_input)-- assert result.cohort_ids == [100, 200]-- # Should apply duration filtering with correct parameters- mock_initial_queryset.filter.assert_called_once_with(- last_calculation_duration_ms__gte=10000, # 10s * 1000- last_calculation_duration_ms__lt=25000, # 25s * 1000- )-- @pytest.mark.asyncio- async def test_selection_activity_with_duration_thresholds_p95_p99(self):- """Should apply normal filtering for p95-p99 percentile range."""- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids={3},- duration_percentile_min=95.0,- duration_percentile_max=99.0,- )-- thresholds = QueryPercentileThresholds(- min_threshold_ms=25000, # 25 seconds minimum- max_threshold_ms=50000, # 50 seconds maximum- )-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_initial_queryset = Mock()- mock_filtered_queryset = Mock()- mock_filtered_queryset.order_by.return_value.values_list.return_value = [300, 400]- mock_initial_queryset.filter.return_value = mock_filtered_queryset-- mock_cohort.objects.filter.return_value = mock_initial_queryset-- activity_input = CohortSelectionActivityInput(- coordinator_inputs=inputs, query_percentile_thresholds=thresholds- )- result = await get_realtime_cohort_selection_activity(activity_input)-- assert result.cohort_ids == [300, 400]-- # Should apply normal range filtering- mock_initial_queryset.filter.assert_called_once_with(- last_calculation_duration_ms__gte=25000, # 25s * 1000- last_calculation_duration_ms__lt=50000, # 50s * 1000- )-- @pytest.mark.asyncio- async def test_selection_activity_with_duration_thresholds_p99_p100(self):- """Should apply p100 filtering (include NULLs) for p99-p100 percentile range."""- from django.db.models import Q-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids={3},- duration_percentile_min=99.0,- duration_percentile_max=100.0, # This triggers is_p100=True- )-- thresholds = QueryPercentileThresholds(- min_threshold_ms=60000, # 60 seconds minimum- max_threshold_ms=120000, # Max doesn't matter for p100- )-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_initial_queryset = Mock()- mock_filtered_queryset = Mock()- mock_filtered_queryset.order_by.return_value.values_list.return_value = [300, 400, 500]- mock_initial_queryset.filter.return_value = mock_filtered_queryset-- mock_cohort.objects.filter.return_value = mock_initial_queryset-- activity_input = CohortSelectionActivityInput(- coordinator_inputs=inputs, query_percentile_thresholds=thresholds- )- result = await get_realtime_cohort_selection_activity(activity_input)-- assert result.cohort_ids == [300, 400, 500]-- # Should apply p100 filtering (Q object with OR condition for NULLs)- mock_initial_queryset.filter.assert_called_once()- filter_args = mock_initial_queryset.filter.call_args[0]- assert len(filter_args) == 1- assert isinstance(filter_args[0], Q)-- @pytest.mark.asyncio- async def test_selection_activity_no_duration_filtering_when_no_thresholds(self):- """Should skip duration filtering when no thresholds provided."""- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids={5},- duration_percentile_min=80.0, # These are set but...- duration_percentile_max=90.0,- )-- # No thresholds provided (e.g., ClickHouse had no data)- thresholds = None-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.order_by.return_value.values_list.return_value = [600, 700]- mock_cohort.objects.filter.return_value = mock_queryset-- activity_input = CohortSelectionActivityInput(- coordinator_inputs=inputs, query_percentile_thresholds=thresholds- )- result = await get_realtime_cohort_selection_activity(activity_input)-- assert result.cohort_ids == [600, 700]-- # Should NOT call filter for duration filtering- # Only the base filter for team_ids should be called- assert mock_queryset.filter.call_count == 0 # No duration filtering-- @pytest.mark.asyncio- async def test_selection_activity_no_duration_filtering_when_no_percentiles(self):- """Should skip duration filtering when percentile parameters not set."""- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- team_ids={7},- # No duration_percentile_min or duration_percentile_max set- )-- thresholds = QueryPercentileThresholds(min_threshold_ms=15, max_threshold_ms=40)-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.order_by.return_value.values_list.return_value = [800, 900]- mock_cohort.objects.filter.return_value = mock_queryset-- activity_input = CohortSelectionActivityInput(- coordinator_inputs=inputs, query_percentile_thresholds=thresholds- )- result = await get_realtime_cohort_selection_activity(activity_input)-- assert result.cohort_ids == [800, 900]-- # Should NOT apply duration filtering because percentile params are None- assert mock_queryset.filter.call_count == 0---class TestCoordinatorWorkflowInsufficientData:- """Tests for coordinator workflow behavior when insufficient duration data exists."""-- @pytest.mark.asyncio- async def test_coordinator_skips_p90_p95_schedule_when_insufficient_data(self):- """Should exit early for p90-p95 schedule when no duration data exists."""- from unittest.mock import AsyncMock-- # Import the coordinator workflow- from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- RealtimeCohortCalculationCoordinatorWorkflow,- RealtimeCohortCalculationCoordinatorWorkflowInputs,- )-- # Create coordinator workflow instance- workflow = RealtimeCohortCalculationCoordinatorWorkflow()-- # Mock workflow execute_activity to return None (insufficient data)- workflow_logger = Mock()-- with (- patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.LOGGER") as mock_logger,- patch("temporalio.workflow.execute_activity", new_callable=AsyncMock) as mock_execute_activity,- patch("temporalio.workflow.time", return_value=1234567890.0), # Mock workflow time- patch("temporalio.workflow.info") as mock_info, # Mock workflow info- ):- mock_logger.bind.return_value = workflow_logger-- # Mock workflow info- mock_info.return_value.workflow_id = "test-workflow-id"-- # Mock the get_query_percentile_thresholds_activity to return None- mock_execute_activity.return_value = None-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- duration_percentile_min=90.0, # p90-p95 schedule- duration_percentile_max=95.0,- )-- # Should exit early without calling get_realtime_cohort_selection_activity- await workflow.run(inputs)-- # Should only call get_query_percentile_thresholds_activity, not cohort selection- assert mock_execute_activity.call_count == 1-- # Verify the correct log message was generated- workflow_logger.info.assert_any_call(- "Skipping p90.0-p95.0 schedule execution: insufficient duration data for percentile filtering"- )-- @pytest.mark.asyncio- async def test_coordinator_skips_p95_p99_schedule_when_insufficient_data(self):- """Should exit early for p95-p99 schedule when no duration data exists."""- from unittest.mock import AsyncMock-- # Import the coordinator workflow- from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- RealtimeCohortCalculationCoordinatorWorkflow,- RealtimeCohortCalculationCoordinatorWorkflowInputs,- )-- # Create coordinator workflow instance- workflow = RealtimeCohortCalculationCoordinatorWorkflow()-- # Mock workflow execute_activity to return None (insufficient data)- workflow_logger = Mock()-- with (- patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.LOGGER") as mock_logger,- patch("temporalio.workflow.execute_activity", new_callable=AsyncMock) as mock_execute_activity,- patch("temporalio.workflow.time", return_value=1234567890.0), # Mock workflow time- patch("temporalio.workflow.info") as mock_info, # Mock workflow info- ):- mock_logger.bind.return_value = workflow_logger-- # Mock workflow info- mock_info.return_value.workflow_id = "test-workflow-id"-- # Mock the get_query_percentile_thresholds_activity to return None- mock_execute_activity.return_value = None-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- duration_percentile_min=95.0, # p95-p99 schedule- duration_percentile_max=99.0,- )-- # Should exit early without calling get_realtime_cohort_selection_activity- await workflow.run(inputs)-- # Should only call get_query_percentile_thresholds_activity, not cohort selection- assert mock_execute_activity.call_count == 1-- # Verify the correct log message was generated- workflow_logger.info.assert_any_call(- "Skipping p95.0-p99.0 schedule execution: insufficient duration data for percentile filtering"- )-- @pytest.mark.asyncio- async def test_coordinator_skips_p99_p100_schedule_when_insufficient_data(self):- """Should exit early for p99-p100 schedule when no duration data exists."""- from unittest.mock import AsyncMock-- # Import the coordinator workflow- from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- RealtimeCohortCalculationCoordinatorWorkflow,- RealtimeCohortCalculationCoordinatorWorkflowInputs,- )-- # Create coordinator workflow instance- workflow = RealtimeCohortCalculationCoordinatorWorkflow()-- # Mock workflow execute_activity to return None (insufficient data)- workflow_logger = Mock()-- with (- patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.LOGGER") as mock_logger,- patch("temporalio.workflow.execute_activity", new_callable=AsyncMock) as mock_execute_activity,- patch("temporalio.workflow.time", return_value=1234567890.0), # Mock workflow time- patch("temporalio.workflow.info") as mock_info, # Mock workflow info- ):- mock_logger.bind.return_value = workflow_logger-- # Mock workflow info- mock_info.return_value.workflow_id = "test-workflow-id"-- # Mock the get_query_percentile_thresholds_activity to return None- mock_execute_activity.return_value = None-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- duration_percentile_min=99.0, # p99-p100 schedule- duration_percentile_max=100.0,- )-- # Should exit early without calling get_realtime_cohort_selection_activity- await workflow.run(inputs)-- # Should only call get_query_percentile_thresholds_activity, not cohort selection- assert mock_execute_activity.call_count == 1-- # Verify the correct log message was generated- workflow_logger.info.assert_any_call(- "Skipping p99.0-p100.0 schedule execution: insufficient duration data for percentile filtering"- )-- @pytest.mark.asyncio- async def test_coordinator_continues_when_insufficient_duration_data(self):- """Should continue processing even when no duration data exists for percentile filtering."""- from unittest.mock import AsyncMock-- # Import the coordinator workflow- from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- RealtimeCohortCalculationCoordinatorWorkflow,- RealtimeCohortCalculationCoordinatorWorkflowInputs,- )-- # Create coordinator workflow instance- workflow = RealtimeCohortCalculationCoordinatorWorkflow()-- # Mock workflow execute_activity- workflow_logger = Mock()-- # Mock cohort selection result with empty cohort list- mock_selection_result = Mock()- mock_selection_result.cohort_ids = []-- with (- patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.LOGGER") as mock_logger,- patch("temporalio.workflow.execute_activity", new_callable=AsyncMock) as mock_execute_activity,- patch("temporalio.workflow.time", return_value=1234567890.0), # Mock workflow time- patch("temporalio.workflow.info") as mock_info, # Mock workflow info- ):- mock_logger.bind.return_value = workflow_logger-- # Mock workflow info- mock_info.return_value.workflow_id = "test-workflow-id"-- # Mock sequence: thresholds=None, selection returns empty list- mock_execute_activity.side_effect = [- None, # get_query_percentile_thresholds_activity returns None- mock_selection_result, # get_realtime_cohort_selection_activity returns empty- ]-- inputs = RealtimeCohortCalculationCoordinatorWorkflowInputs(- duration_percentile_min=0.0, # Test with wide percentile range- duration_percentile_max=90.0,- )-- # Should continue processing and call both activities- await workflow.run(inputs)-- # Should call both get_query_percentile_thresholds_activity AND get_realtime_cohort_selection_activity- assert mock_execute_activity.call_count == 2-- # Verify no early exit message was generated- workflow_logger.info.assert_any_call(- "Duration percentile filtering p0.0-p90.0: disabled (no historical query data)"- )---class TestBatchUpdateCohortMetrics:- """Tests for _batch_update_cohort_metrics timestamp handling regression."""-- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_batch_update_cohort_metrics_timestamp_fix(self):- """- Regression test for timestamp bug fix.-- - Asserts last_backfill_person_properties_at is NOT updated- - Asserts last_realtime_cohort_calculation_at IS updated- - Asserts last_calculation_duration_ms updates respect the DURATION_UPDATE_RELATIVE_THRESHOLD- """- from datetime import timedelta-- from django.utils import timezone-- from asgiref.sync import sync_to_async-- from posthog.models.organization import Organization- from posthog.models.team.team import Team-- from products.cohorts.backend.models.cohort import Cohort, CohortType-- # Create test organization and team- organization = await sync_to_async(Organization.objects.create)(name="Test Organization")- team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)-- # Set fixed timestamps for comparison- initial_backfill_time = timezone.now() - timedelta(hours=24)- initial_realtime_time = timezone.now() - timedelta(hours=12)-- # Create test cohorts with various duration scenarios- cohort1 = await sync_to_async(Cohort.objects.create)(- name="Cohort 1",- team=team,- cohort_type=CohortType.REALTIME,- last_backfill_person_properties_at=initial_backfill_time,- last_realtime_cohort_calculation_at=initial_realtime_time,- last_calculation_duration_ms=1000, # 1 second- )-- cohort2 = await sync_to_async(Cohort.objects.create)(- name="Cohort 2",- team=team,- cohort_type=CohortType.REALTIME,- last_backfill_person_properties_at=initial_backfill_time,- last_realtime_cohort_calculation_at=initial_realtime_time,- last_calculation_duration_ms=2000, # 2 seconds- )-- # Prepare duration updates- # Cohort 1: Small change below threshold (should NOT update duration)- new_duration_1 = 1100 # 10% change, below DURATION_UPDATE_RELATIVE_THRESHOLD (25%)-- # Cohort 2: Large change above threshold (should update duration)- new_duration_2 = 3000 # 50% change, above DURATION_UPDATE_RELATIVE_THRESHOLD (25%)-- cohort_durations = {cohort1.id: new_duration_1, cohort2.id: new_duration_2}-- # Execute the function- duration_updates_count = await _batch_update_cohort_metrics(cohort_durations)-- # Refresh cohorts from database- await sync_to_async(cohort1.refresh_from_db)()- await sync_to_async(cohort2.refresh_from_db)()-- # Assert last_backfill_person_properties_at is NOT updated- assert cohort1.last_backfill_person_properties_at == initial_backfill_time- assert cohort2.last_backfill_person_properties_at == initial_backfill_time-- # Assert last_realtime_cohort_calculation_at IS updated for both- assert cohort1.last_realtime_cohort_calculation_at > initial_realtime_time- assert cohort2.last_realtime_cohort_calculation_at > initial_realtime_time-- # Assert duration updates respect the DURATION_UPDATE_RELATIVE_THRESHOLD- # Cohort 1: small change, should NOT update duration- assert cohort1.last_calculation_duration_ms == 1000 # Original value-- # Cohort 2: large change, should update duration- assert cohort2.last_calculation_duration_ms == 3000 # New value-- # Assert correct count of duration updates- assert duration_updates_count == 1 # Only cohort2 should have had duration updated-- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_batch_update_cohort_metrics_first_calculation(self):- """Test that first calculation always updates duration regardless of threshold."""- from asgiref.sync import sync_to_async-- from posthog.models.organization import Organization- from posthog.models.team.team import Team-- from products.cohorts.backend.models.cohort import Cohort, CohortType-- # Create test organization and team- organization = await sync_to_async(Organization.objects.create)(name="Test Organization")- team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)-- cohort = await sync_to_async(Cohort.objects.create)(- name="New Cohort",- team=team,- cohort_type=CohortType.REALTIME,- last_calculation_duration_ms=None, # No previous calculation- )-- initial_realtime_time = cohort.last_realtime_cohort_calculation_at-- # Prepare first duration- first_duration = 5000 # 5 seconds- cohort_durations = {cohort.id: first_duration}-- # Execute the function- duration_updates_count = await _batch_update_cohort_metrics(cohort_durations)-- # Refresh cohort from database- await sync_to_async(cohort.refresh_from_db)()-- # Assert last_realtime_cohort_calculation_at IS updated- assert cohort.last_realtime_cohort_calculation_at != initial_realtime_time-- # Assert duration is updated for first calculation- assert cohort.last_calculation_duration_ms == 5000-- # Assert correct count- assert duration_updates_count == 1-- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_batch_update_cohort_metrics_zero_previous_duration(self):- """Test that cohorts with zero previous duration always get updated."""- from asgiref.sync import sync_to_async-- from posthog.models.organization import Organization- from posthog.models.team.team import Team-- from products.cohorts.backend.models.cohort import Cohort, CohortType-- # Create test organization and team- organization = await sync_to_async(Organization.objects.create)(name="Test Organization")- team = await sync_to_async(Team.objects.create)(name="Test Team", organization=organization)-- cohort = await sync_to_async(Cohort.objects.create)(- name="Zero Duration Cohort",- team=team,- cohort_type=CohortType.REALTIME,- last_calculation_duration_ms=0, # Zero previous duration- )-- # Prepare new duration- new_duration = 100 # Small value- cohort_durations = {cohort.id: new_duration}-- # Execute the function- duration_updates_count = await _batch_update_cohort_metrics(cohort_durations)-- # Refresh cohort from database- await sync_to_async(cohort.refresh_from_db)()-- # Assert duration is updated even though change is small (because previous was 0)- assert cohort.last_calculation_duration_ms == 100-- # Assert correct count- assert duration_updates_count == 1---class TestFinalQueryMembershipStatuses:- """Tests for the final_query membership diff logic.-- The query determines 'entered'/'left' via a FULL OUTER JOIN between- current cohort matches and the previous cohort_membership state.- These tests verify that status assignment and filtering are correct- for each membership scenario without requiring a live ClickHouse.- """-- @pytest.mark.parametrize(- "rows,expected_statuses",- [- # New members only → all 'entered'- (- [{"person_id": "aaa", "status": "entered"}, {"person_id": "bbb", "status": "entered"}],- {"aaa": "entered", "bbb": "entered"},- ),- # Departing members only → all 'left'- (- [{"person_id": "ccc", "status": "left"}, {"person_id": "ddd", "status": "left"}],- {"ccc": "left", "ddd": "left"},- ),- # Mixed- (- [{"person_id": "eee", "status": "entered"}, {"person_id": "fff", "status": "left"}],- {"eee": "entered", "fff": "left"},- ),- # No changes → empty (WHERE clause filters out unchanged rows)- ([], {}),- ],- )- def test_only_entered_and_left_statuses_are_emitted(self, rows, expected_statuses):- """The WHERE clause must exclude 'unchanged' rows; only 'entered'/'left' reach the activity loop.-- Note: this test operates on hand-built row dicts, not on query output. An execution-level- test seeding cohort_membership with entered/left/unchanged persons and asserting the- unchanged one is dropped would give stronger coverage but requires a ClickHouse harness- that this suite (which mocks Kafka) does not have. Track separately if desired.- """- observed: dict[str, str] = {}-- for row in rows:- status = row["status"]- assert status in ("entered", "left"), (- f"Query should only emit 'entered' or 'left'; got {status!r}. "- "'unchanged' rows must be filtered out by the WHERE clause."- )- observed[row["person_id"]] = status-- assert observed == expected_statuses-- def test_build_final_query_contains_expected_predicates(self):- """build_final_query must contain the key SQL predicates from the optimized query.-- Asserts that regressions (e.g. reverting to CASE/ELSE or GROUP BY team_id) are caught- by directly inspecting the produced SQL.- """- sql = build_final_query("SELECT id FROM nowhere")-- # Status is computed with if(), not CASE ... ELSE 'unchanged'- assert "if(previous_members.person_id IS NULL, 'entered', 'left')" in sql- assert "CASE" not in sql- assert "'unchanged'" not in sql-- # Unchanged rows are filtered by NULL checks, not a string IN list- assert "(previous_members.person_id IS NULL) OR (current_matches.id IS NULL)" in sql- assert "status IN" not in sql-- # cohort_membership subquery groups only by person_id, not team_id- assert "GROUP BY person_id" in sql- assert "GROUP BY team_id" not in sql-- # The inner subquery is embedded correctly- assert "SELECT id FROM nowhere" in sql-- # GROUP BY spill settings (the OOM fix) must survive future edits to build_final_query- assert "join_use_nulls = 1" in sql- assert "max_bytes_ratio_before_external_group_by = 0.5" in sql- assert "distributed_aggregation_memory_efficient = 1" in sql-- def test_if_expression_matches_full_outer_join_semantics(self):- """The if() expression and WHERE clause encode the FULL OUTER JOIN membership diff contract.-- - NULL previous_person_id → person is new → 'entered'- - NULL current_id → person departed → 'left'- - Both non-NULL → unchanged → excluded by WHERE- """-- def compute_status(previous_person_id, current_id):- """Mirrors: if(previous_members.person_id IS NULL, 'entered', 'left')"""- return "entered" if previous_person_id is None else "left"-- def passes_where(previous_person_id, current_id):- """Mirrors: WHERE (previous_members.person_id IS NULL) OR (current_matches.id IS NULL)"""- return (previous_person_id is None) or (current_id is None)-- pid = "person-abc"-- # New member: present in current, absent from previous → WHERE passes, status 'entered'- assert passes_where(None, pid) is True- assert compute_status(None, pid) == "entered"-- # Departing member: present in previous, absent from current → WHERE passes, status 'left'- assert passes_where(pid, None) is True- assert compute_status(pid, None) == "left"-- # Unchanged member: present in both → WHERE filters it out entirely- assert passes_where(pid, pid) is False---class _AsyncClientContextManager:- def __init__(self, client: Mock) -> None:- self.client = client-- async def __aenter__(self) -> Mock:- return self.client-- async def __aexit__(- self,- exc_type: type[BaseException] | None,- exc_value: BaseException | None,- traceback: TracebackType | None,- ) -> None:- return None---class _NoopHeartbeater:- def __init__(self, details: tuple[str, ...] = (), factor: int = 120) -> None:- self.details = details-- async def __aenter__(self) -> "_NoopHeartbeater":- return self-- async def __aexit__(- self,- exc_type: type[BaseException] | None,- exc_value: BaseException | None,- traceback: TracebackType | None,- ) -> None:- return None---class TestRealtimeCohortConcurrencyGate:- @pytest.mark.asyncio- async def test_activity_opens_clickhouse_client_through_gated_wrapper(self):- # Guards the concurrency cap for the one gated site the other six tests don't execute:- # if this activity's ClickHouse access stops flowing through get_messaging_client (the exact- # way the production 202 could recur), clickhouse_concurrency.get_client is no longer the- # symbol invoked and this assertion fails.- # `yield` after `return` never runs, but its presence makes this an async generator that- # streams zero rows — matching stream_query_as_jsonl's shape.- async def empty_stream(*args, **kwargs):- return- yield-- mock_client = Mock()- mock_client.stream_query_as_jsonl = lambda *args, **kwargs: empty_stream()-- cohort = Mock()- cohort.pk = 10- cohort.team_id = 1- cohort.team = Mock()- cohort.name = "realtime cohort"-- cohort_model = Mock()- cohort_model.objects.filter.return_value.select_related.return_value = [cohort]-- get_client_mock = Mock(return_value=_AsyncClientContextManager(mock_client))- module = "posthog.temporal.messaging.realtime_cohort_calculation_workflow"-- with (- patch("posthog.temporal.messaging.clickhouse_concurrency.get_client", get_client_mock),- patch(f"{module}.Cohort", cohort_model),- patch(f"{module}.HogQLRealtimeCohortQuery"),- patch(f"{module}.prepare_and_print_ast", return_value=("SELECT 1", {})),- patch(f"{module}.get_producer", return_value=Mock()),- patch(f"{module}.Heartbeater", _NoopHeartbeater),- patch(f"{module}._batch_update_cohort_metrics", AsyncMock(return_value=0)),- patch(f"{module}.get_cohort_calculation_success_metric", return_value=Mock()),- patch(f"{module}.get_cohort_calculation_failure_metric", return_value=Mock()),- ):- await process_realtime_cohort_calculation_activity(RealtimeCohortCalculationWorkflowInputs(cohort_id=10))-- get_client_mock.assert_called_once_with(team_id=1)diff --git a/posthog/temporal/messaging/test/test_reconcile_precalculated_data_workflow.py b/posthog/temporal/messaging/test/test_reconcile_precalculated_data_workflow.pydeleted file mode 100644index 64e13bfc0ae1..000000000000--- a/posthog/temporal/messaging/test/test_reconcile_precalculated_data_workflow.py+++ /dev/null@@ -1,688 +0,0 @@-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 (- DEFAULT_OVERRIDES_LOOKBACK_HOURS,- 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=DEFAULT_OVERRIDES_LOOKBACK_HOURS)- <= result.since- <= after - dt.timedelta(hours=DEFAULT_OVERRIDES_LOOKBACK_HOURS)- )---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/messaging/test/test_threshold_calculation_math.py b/posthog/temporal/messaging/test/test_threshold_calculation_math.pydeleted file mode 100644index 2940434ef501..000000000000--- a/posthog/temporal/messaging/test/test_threshold_calculation_math.py+++ /dev/null@@ -1,257 +0,0 @@-"""-Tests for mathematical correctness of threshold calculations with caching.--Verifies that the integration between quantiles caching and threshold calculation-produces consistent, non-overlapping tier boundaries.-"""--import statistics--import pytest-from unittest.mock import Mock, patch--from posthog.temporal.messaging.quantiles_storage import CachedQuantiles-from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (- QueryPercentileThresholdsInput,- calculate_percentile_thresholds,-)---class TestThresholdCalculationMath:- """Test mathematical correctness of threshold calculations."""-- @pytest.mark.parametrize(- "durations,description",- [- (- [- 100,- 150,- 200,- 250,- 300,- 350,- 400,- 450,- 500,- 550,- 600,- 650,- 700,- 750,- 800,- 850,- 900,- 950,- 1000,- 1050,- 1100,- 1200,- 1300,- 1400,- 1500,- 1600,- 1700,- 1800,- 1900,- 2000,- 2200,- 2400,- 2600,- 2800,- 3000,- 3200,- 3400,- 3600,- 3800,- 4000,- 4500,- 5000,- 5500,- 6000,- 6500,- 7000,- 7500,- 8000,- 8500,- 9000,- 10000,- 12000,- 14000,- 16000,- 18000,- 20000,- 25000,- 30000,- 40000,- 50000,- ],- "realistic cohort durations",- ),- (- [- 100,- 150,- 200,- 250,- 300,- 350,- 400,- 450,- 498,- 501,- 520,- 540,- 560,- 580,- 601,- 650,- 700,- 800,- 900,- 1000,- 1200,- 1500,- 2000,- ],- "problematic scenario from bug report",- ),- ],- )- @pytest.mark.asyncio- async def test_tier_boundaries_no_overlap_with_caching(self, durations, description):- """Test that cached quantiles produce non-overlapping tier boundaries."""- expected_quantiles = statistics.quantiles(durations, n=100, method="inclusive")- expected_max = int(max(durations))-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = durations- mock_cohort.objects.filter.return_value = mock_queryset-- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate"- ) as mock_get_quantiles:- mock_get_quantiles.return_value = CachedQuantiles(quantiles=expected_quantiles, max_value=expected_max)-- # Calculate thresholds for all tiers- p0_p50_input = QueryPercentileThresholdsInput(min_percentile=0.0, max_percentile=50.0)- p50_p80_input = QueryPercentileThresholdsInput(min_percentile=50.0, max_percentile=80.0)- p80_p90_input = QueryPercentileThresholdsInput(min_percentile=80.0, max_percentile=90.0)- p90_p100_input = QueryPercentileThresholdsInput(min_percentile=90.0, max_percentile=100.0)-- p0_p50_thresholds = await calculate_percentile_thresholds(p0_p50_input)- p50_p80_thresholds = await calculate_percentile_thresholds(p50_p80_input)- p80_p90_thresholds = await calculate_percentile_thresholds(p80_p90_input)- p90_p100_thresholds = await calculate_percentile_thresholds(p90_p100_input)-- # Verify all calculations succeeded- assert p0_p50_thresholds is not None- assert p50_p80_thresholds is not None- assert p80_p90_thresholds is not None- assert p90_p100_thresholds is not None-- # Verify tier boundaries align perfectly (no gaps or overlaps)- assert p0_p50_thresholds.min_threshold_ms == 0 # p0 is always 0- assert p0_p50_thresholds.max_threshold_ms == p50_p80_thresholds.min_threshold_ms, (- f"{description} - p0-p50 max ({p0_p50_thresholds.max_threshold_ms}) should equal p50-p80 min ({p50_p80_thresholds.min_threshold_ms})"- )- assert p50_p80_thresholds.max_threshold_ms == p80_p90_thresholds.min_threshold_ms, (- f"{description} - p50-p80 max ({p50_p80_thresholds.max_threshold_ms}) should equal p80-p90 min ({p80_p90_thresholds.min_threshold_ms})"- )- assert p80_p90_thresholds.max_threshold_ms == p90_p100_thresholds.min_threshold_ms, (- f"{description} - p80-p90 max ({p80_p90_thresholds.max_threshold_ms}) should equal p90-p100 min ({p90_p100_thresholds.min_threshold_ms})"- )-- # Verify p100 is the actual maximum- assert p90_p100_thresholds.max_threshold_ms == max(durations), (- f"{description} - p100 value ({p90_p100_thresholds.max_threshold_ms}) should equal max duration ({max(durations)})"- )-- @pytest.mark.asyncio- async def test_consistent_calculations_across_calls(self):- """Test that multiple calls with same cache return identical results."""- durations = list(range(100, 2000, 50)) # Clean test data-- expected_quantiles = statistics.quantiles(durations, n=100, method="inclusive")- expected_max = int(max(durations))-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = durations- mock_cohort.objects.filter.return_value = mock_queryset-- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate"- ) as mock_get_quantiles:- # Ensure cache returns same quantiles every time- mock_get_quantiles.return_value = CachedQuantiles(quantiles=expected_quantiles, max_value=expected_max)-- # Multiple workflows calculating p50-p80 thresholds- input_data = QueryPercentileThresholdsInput(min_percentile=50.0, max_percentile=80.0)-- result1 = await calculate_percentile_thresholds(input_data)- result2 = await calculate_percentile_thresholds(input_data)- result3 = await calculate_percentile_thresholds(input_data)-- # All results should be identical- assert result1 is not None- assert result2 is not None- assert result3 is not None- assert result1.min_threshold_ms == result2.min_threshold_ms == result3.min_threshold_ms- assert result1.max_threshold_ms == result2.max_threshold_ms == result3.max_threshold_ms-- # Cache should only be called once per calculation (or multiple times but returning same data)- assert mock_get_quantiles.call_count >= 3-- @pytest.mark.asyncio- async def test_percentile_edge_cases(self):- """Test edge cases in percentile calculations."""- durations = [500, 1000, 1500] # Minimal data-- expected_quantiles = statistics.quantiles(durations, n=100, method="inclusive")- expected_max = int(max(durations))-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = durations- mock_cohort.objects.filter.return_value = mock_queryset-- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate"- ) as mock_get_quantiles:- mock_get_quantiles.return_value = CachedQuantiles(quantiles=expected_quantiles, max_value=expected_max)-- # Test p0 edge case- p0_input = QueryPercentileThresholdsInput(min_percentile=0.0, max_percentile=10.0)- p0_result = await calculate_percentile_thresholds(p0_input)- assert p0_result is not None- assert p0_result.min_threshold_ms == 0 # p0 should always be 0-- # Test p100 edge case- p100_input = QueryPercentileThresholdsInput(min_percentile=99.0, max_percentile=100.0)- p100_result = await calculate_percentile_thresholds(p100_input)- assert p100_result is not None- assert p100_result.max_threshold_ms == max(durations) # p100 should be actual max-- @pytest.mark.asyncio- async def test_threshold_calculation_with_cache_failure(self):- """Test threshold calculation when cache fails."""- durations = [100, 200, 300, 400, 500]-- with patch("posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.Cohort") as mock_cohort:- mock_queryset = Mock()- mock_queryset.values_list.return_value = durations- mock_cohort.objects.filter.return_value = mock_queryset-- with patch(- "posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator.get_cached_quantiles_or_calculate"- ) as mock_get_quantiles:- # Simulate cache failure- mock_get_quantiles.return_value = None-- input_data = QueryPercentileThresholdsInput(min_percentile=25.0, max_percentile=75.0)- result = await calculate_percentile_thresholds(input_data)-- # Should return None when quantiles calculation fails- assert result is Nonediff --git a/posthog/temporal/messaging/types.py b/posthog/temporal/messaging/types.pydeleted file mode 100644index f424bab9d25b..000000000000--- a/posthog/temporal/messaging/types.py+++ /dev/null@@ -1,29 +0,0 @@-"""-Shared types for messaging workflows.-"""--import dataclasses-from typing import Any---class PersonPropertyFilter:- """Person property filter to evaluate."""-- condition_hash: str- bytecode: list[Any] # HogQL bytecode- cohort_ids: list[int] # Cohorts that use this condition- property_key: str | None # The person property key (e.g., 'email', '$host')---class BehavioralEventFilter:- """Behavioral event filter for backfilling precalculated events."""-- condition_hash: str- bytecode: list[Any] # HogQL bytecode- cohort_ids: list[int] # Cohorts that use this condition- event_name: str # Target event name (e.g., '$pageview')- time_value: int # Lookback window size (e.g., 30)- time_interval: str # Lookback window unit (e.g., 'day', 'week', 'month')- event_filters: list[dict] | None = None # Optional per-event property sub-filtersdiff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex b44bcd570933..b4b62d411e32 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -462,7 +462,7 @@ async def create_wa_weekly_digest_schedule(client: Client):"wa-weekly-digest",WAWeeklyDigestInput(),id="wa-weekly-digest-schedule",- task_queue=settings.MESSAGING_TASK_QUEUE,+ task_queue=settings.WEEKLY_DIGEST_TASK_QUEUE,retry_policy=common.RetryPolicy(maximum_attempts=1,),@@ -497,7 +497,7 @@ async def create_wa_digest_notification_schedule(client: Client):"wa-digest-notification",WADigestNotificationInput(),id="wa-digest-notification-schedule",- task_queue=settings.MESSAGING_TASK_QUEUE,+ task_queue=settings.WEEKLY_DIGEST_TASK_QUEUE,retry_policy=common.RetryPolicy(maximum_attempts=1,),@@ -645,8 +645,8 @@ async def cleanup_cohort_calculation_schedules(client: Client):and owns reconciliation too (its workers/reconcile.rs and sweep/reconcile.rs), so nothing hereneeds to run on a cadence any more.- The workflows stay registered on the messaging worker only until the Python implementation is- deleted. In-flight executions finish on their own; deleting a schedule doesn't cancel them.+ The Python implementation is gone; this remains only to reap schedules in regions that+ haven't converged yet, and is safe to delete once they all have."""legacy_schedule_ids = ["realtime-cohort-calculation-p0-p50",diff --git a/posthog/temporal/tests/test_schedule.py b/posthog/temporal/tests/test_schedule.pynew file mode 100644index 000000000000..8bfbf665d6a1--- /dev/null+++ b/posthog/temporal/tests/test_schedule.py@@ -0,0 +1,38 @@+import pytest+from unittest import mock++from django.conf import settings+from django.test import override_settings++from temporalio.client import Schedule, ScheduleActionStartWorkflow++from posthog.temporal.schedule import create_wa_digest_notification_schedule, create_wa_weekly_digest_schedule+++# Both WA digest schedules pin their task queue, and the worker registers those workflows on+# WEEKLY_DIGEST_TASK_QUEUE. If a later edit repoints or hardcodes only the schedule side, the+# schedules fire into a queue nobody polls, which stays invisible for a week because both digests are+# weekly. The setting is overridden to a distinct value because every task queue setting collapses to+# one shared dev queue under DEBUG, so asserting against the un-overridden symbol would also pass if+# the schedules pointed at some other queue's setting.+@override_settings(WEEKLY_DIGEST_TASK_QUEUE="weekly-digest-task-queue-under-test")+async def test_wa_digest_schedules_target_the_weekly_digest_queue() -> None:+ captured: list[Schedule] = []++ with (+ mock.patch("posthog.temporal.schedule.a_schedule_exists", new=mock.AsyncMock(return_value=False)),+ mock.patch(+ "posthog.temporal.schedule.a_create_schedule",+ new=mock.AsyncMock(side_effect=lambda client, schedule_id, schedule, **kwargs: captured.append(schedule)),+ ),+ ):+ await create_wa_weekly_digest_schedule(mock.MagicMock())+ await create_wa_digest_notification_schedule(mock.MagicMock())++ task_queues: list[str] = []+ for schedule in captured:+ assert isinstance(schedule.action, ScheduleActionStartWorkflow)+ task_queues.append(schedule.action.task_queue)++ assert task_queues == [settings.WEEKLY_DIGEST_TASK_QUEUE] * 2diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex ebda2955c7b2..a6f06c4c1b36 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -507,8 +507,8 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):- Cohorts with behavioral event filters require last_backfill_events_at- Cohorts with both require both timestamps- Cohorts with neither recognized filter type (empty filters, cohort-reference-only, etc.)- are not flag-compatible, even if stale timestamps are set, because HogQLRealtimeCohortQuery- cannot evaluate them.+ are not flag-compatible, even if stale timestamps are set, because the realtime+ evaluator has no leaf to key membership on."""if self.cohort_type != CohortType.REALTIME:return Falsediff --git a/rust/cohort-core/src/hogvm/executor.rs b/rust/cohort-core/src/hogvm/executor.rsindex c04f932edc74..2bf2ccfd12c3 100644--- a/rust/cohort-core/src/hogvm/executor.rs+++ b/rust/cohort-core/src/hogvm/executor.rs@@ -1,5 +1,6 @@//! Run compiled cohort-filter bytecode through `hogvm::sync_execute`, coercing the result to the-//! boolean Stage 1 needs (matching the Node consumer's `execResult?.result ?? false`).+//! boolean Stage 1 needs (matching `nodejs/src/cdp/utils/hog-exec.ts`'s+//! `execResult?.result ?? false`).//!//! The hot path reuses one [`CohortEvaluator`] per event: the STL context and globals are set once//! and only the program is swapped per condition, amortizing the context build across all conditions.diff --git a/rust/cohort-core/src/hogvm/mod.rs b/rust/cohort-core/src/hogvm/mod.rsindex c3938e4d95de..78bb8a17c024 100644--- a/rust/cohort-core/src/hogvm/mod.rs+++ b/rust/cohort-core/src/hogvm/mod.rs@@ -1,5 +1,5 @@//! Evaluate compiled cohort-filter bytecode against an event, coercing non-bool results to-//! `false` to match the Node consumer.+//! `false` to match `@posthog/hogvm`'s semantics.//!//! ## Metric-emission contract//!diff --git a/rust/cohort-event-shuffler/src/consumer.rs b/rust/cohort-event-shuffler/src/consumer.rsindex 56e177b7d7f5..cd69f5a59694 100644--- a/rust/cohort-event-shuffler/src/consumer.rs+++ b/rust/cohort-event-shuffler/src/consumer.rs@@ -1,7 +1,7 @@//! Pipelined consume → filter → re-key → produce loop for `clickhouse_events_json`.//!//! Drops events with no `person_id`, skips teams with no realtime cohorts, then re-keys the-//! survivors by `(team_id, person_id)` to match the Node CDP precalculated-filters gating.+//! survivors by `(team_id, person_id)`, gating on the realtime-cohort filter catalog.//!//! Consume, produce-ack, and offset-commit are decoupled: the single owner task enqueues//! survivors without awaiting delivery, resolves acks as they arrive, and periodically commits