:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add managed warehouse product intent and activation (#73906)
Anna Szellcedd4f42f2f5
diff --git a/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx b/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsxindex 7882ff4e9ec8..2d63fa0b75c0 100644--- a/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx+++ b/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx@@ -125,6 +125,8 @@ export interface CodeSnippetProps {thing?: string/** If set, the snippet becomes expandable when there's more than this number of lines. */maxLinesWithoutExpansion?: number+ /** Called after the snippet contents are copied to the clipboard. Useful for telemetry. */+ onCopy?: () => void}export const CodeSnippet = React.memo(function CodeSnippet({@@ -136,6 +138,7 @@ export const CodeSnippet = React.memo(function CodeSnippet({actions,thing = 'snippet',maxLinesWithoutExpansion,+ onCopy,}: CodeSnippetProps): JSX.Element | null {const [expanded, setExpanded] = useState(false)@@ -160,6 +163,7 @@ export const CodeSnippet = React.memo(function CodeSnippet({if (text) {e.stopPropagation()void copyToClipboard(text, thing)+ onCopy?.()}}}size={compact ? 'small' : 'medium'}diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 80e4d3ae5caf..1677bfcb538e 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -34785,6 +34785,7 @@"selected connector","sql editor empty state","data warehouse sources table",+ "managed warehouse provisioned","experiment created","experiment analyzed","experiment view recordings",@@ -34953,6 +34954,7 @@"llm_evaluations","llm_prompts","logs",+ "managed_warehouse","marketing_analytics","max","mcp_analytics",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 4f63fdd4a55d..0e0d6a4bf43f 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -8638,6 +8638,7 @@ export enum ProductKey {LLM_EVALUATIONS = 'llm_evaluations',LLM_PROMPTS = 'llm_prompts',LOGS = 'logs',+ MANAGED_WAREHOUSE = 'managed_warehouse',MARKETING_ANALYTICS = 'marketing_analytics',MAX = 'max',MCP_ANALYTICS = 'mcp_analytics',@@ -8682,6 +8683,9 @@ export enum ProductIntentContext {SQL_EDITOR_EMPTY_STATE = 'sql editor empty state',DATA_WAREHOUSE_SOURCES_TABLE = 'data warehouse sources table',+ // Managed Warehouse+ MANAGED_WAREHOUSE_PROVISIONED = 'managed warehouse provisioned',+// ExperimentsEXPERIMENT_CREATED = 'experiment created',EXPERIMENT_ANALYZED = 'experiment analyzed',diff --git a/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx b/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsxindex 204bcb583af0..618111378941 100644--- a/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx+++ b/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'import { IconCheck, IconX } from '@posthog/icons'@@ -71,7 +72,12 @@ function ConnectionDetails({ connection }: { connection: WarehouseConnectionApi</div><div><LemonLabel>Connect with psql</LemonLabel>- <CodeSnippet compact wrap thing="psql command">+ <CodeSnippet+ compact+ wrap+ thing="psql command"+ onCopy={() => posthog.capture('managed warehouse connection details copied')}+ >{psqlCmd}</CodeSnippet></div>diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.tsindex 2804e1dae959..9ce1e64fe55e 100644--- a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts+++ b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts@@ -1,10 +1,13 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { addProductIntent } from 'lib/utils/product-intents'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { teamLogic } from 'scenes/teamLogic'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { Region } from '~/types'import {@@ -19,6 +22,7 @@ import {} from 'products/data_warehouse/frontend/generated/api'import type { WarehouseStatusResponseApi } from 'products/data_warehouse/frontend/generated/api.schemas'+import type { WarehouseStatusResponseStateEnumApi } from '../../../../../products/data_warehouse/frontend/generated/api.schemas'import type { PreflightStatus } from '../../../types'// The warehouse name becomes the connection's SNI subdomain (a DNS-1123 label), so it@@ -76,6 +80,7 @@ export interface warehouseProvisioningLogicValues {orgDeletionFailed: booleanorgDeletionSucceeded: booleanpollingActive: boolean+ previousWarehouseState: WarehouseStatusResponseApi['state'] | nullretryDatabaseName: stringschemaName: stringschemaNameAvailable: boolean | null@@ -162,6 +167,9 @@ export interface warehouseProvisioningLogicActions {setLastRequestedDatabaseName: (name: string | null) => {name: string | null}+ setPreviousWarehouseState: (state: WarehouseStatusResponseApi['state'] | null) => {+ state: WarehouseStatusResponseStateEnumApi | null+ }setSchemaName: (name: string) => {name: string}@@ -232,6 +240,7 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([checkDatabaseName: (name: string) => ({ name }),setDatabaseNameAvailable: (available: boolean | null) => ({ available }),setDatabaseNameChecking: (checking: boolean) => ({ checking }),+ setPreviousWarehouseState: (state: WarehouseStatusResponseApi['state'] | null) => ({ state }),setSchemaName: (name: string) => ({ name }),checkSchemaName: (name: string) => ({ name }),setSchemaNameAvailable: (available: boolean | null) => ({ available }),@@ -363,6 +372,15 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([resetPasswordComplete: () => false,},],+ // Tracks the last observed provisioning state so we can emit lifecycle telemetry+ // only on genuine transitions (e.g. provisioning -> ready), not on every 10s poll+ // or on mount for a warehouse that was already provisioned in a previous session.+ previousWarehouseState: [+ null as WarehouseStatusResponseApi['state'] | null,+ {+ setPreviousWarehouseState: (_, { state }) => state,+ },+ ],schemaName: ['',{@@ -556,6 +574,9 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([provisionWarehouse: async ({ databaseName, schemaName }) => {actions.setLastRequestedDatabaseName(databaseName)window.localStorage.setItem(databaseNameStorageKey(teamLogic.values.currentTeamId), databaseName)+ posthog.capture('managed warehouse provision started', {+ is_retry: values.warehouseStatus?.state === 'failed',+ })try {const result = await dataWarehouseProvisionCreate(currentProjectId(), {database_name: databaseName,@@ -564,6 +585,12 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([if (result.password) {actions.setInitialPassword(result.password)}+ // Requesting a managed warehouse is a deliberate, settings-deep action, so it's+ // our genuine intent signal for this product (distinct from data warehouse imports).+ addProductIntent({+ product_type: ProductKey.MANAGED_WAREHOUSE,+ intent_context: ProductIntentContext.MANAGED_WAREHOUSE_PROVISIONED,+ })lemonToast.success('Warehouse provisioning started')actions.loadWarehouseStatus()actions.pollStatus()@@ -610,6 +637,7 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([if (result.password) {actions.setInitialPassword(result.password)}+ posthog.capture('managed warehouse password reset')lemonToast.success('Password has been reset')} catch (e: any) {lemonToast.error(`Failed to reset password: ${e.message || 'Unknown error'}`)@@ -619,6 +647,7 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([deprovisionWarehouse: async () => {window.localStorage.removeItem(databaseNameStorageKey(teamLogic.values.currentTeamId))+ posthog.capture('managed warehouse deprovision started')try {await dataWarehouseDeprovisionCreate(currentProjectId())lemonToast.success('Warehouse deprovisioning started')@@ -658,6 +687,18 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([loadWarehouseStatusSuccess: ({ warehouseStatus }) => {const state = warehouseStatus?.state+ // Emit outcome telemetry only on genuine transitions, comparing against the+ // previously observed state (see the `previousWarehouseState` reducer) — not on+ // every 10s poll or on mount for a warehouse already provisioned earlier.+ const previousState = values.previousWarehouseState+ if ((previousState === 'pending' || previousState === 'provisioning') && state === 'ready') {+ posthog.capture('managed warehouse provisioned')+ }+ if (previousState === 'deleting' && state === 'deleted') {+ posthog.capture('managed warehouse deprovisioned')+ }+ actions.setPreviousWarehouseState(state ?? null)+if (state === 'deleted') {actions.setLastRequestedDatabaseName(null)window.localStorage.removeItem(databaseNameStorageKey(teamLogic.values.currentTeamId))diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.pyindex 18d91eaff98c..c44eee0831d2 100644--- a/posthog/models/product_intent/product_intent.py+++ b/posthog/models/product_intent/product_intent.py@@ -1,5 +1,5 @@from collections.abc import Callable-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Any, Optionalfrom django.core.cache import cache@@ -58,6 +58,48 @@ is created won't have tracking events sent for them. Unless you want to solve thmake activation metrics require multiple things to happen."""+# Activation threshold for the managed warehouse: a warehouse that is provisioned but never+# queried still emits small idle compute heartbeats, so we require meaningful compute before+# counting the team as activated. Provisional value drawn from PostHog's own dogfood warehouse+# (the only one with data today); retune once real customer warehouses report usage.+MANAGED_WAREHOUSE_ACTIVATION_CPU_SECONDS = 100_000+MANAGED_WAREHOUSE_ACTIVATION_WINDOW_DAYS = 30+# Throttle the (ClickHouse-backed) managed warehouse activation check to at most once per hour+# per team, since register() runs it synchronously on every intent PATCH. Activation is sticky+# and also re-evaluated by the daily calculate_product_activation task, so an hour of latency+# on first activation is harmless.+MANAGED_WAREHOUSE_ACTIVATION_CHECK_TTL_SECONDS = 60 * 60+++def get_managed_warehouse_compute_usage(team_id: int, start: datetime, end: datetime) -> float:+ # Sums cpu_seconds from the `managed warehouse compute usage` heartbeat (emitted by the+ # external duckgres service into the owning project) over the [start, end) window.+ #+ # Trust note: this is a public capture event and carries no non-public provenance signal+ # today (its `token` property is the public project token), so a customer could forge it to+ # inflate their own activation metric. Blast radius is limited to that team's activation+ # state — no cross-tenant, billing, or security impact. Hardening path: have duckgres attach+ # an internal shared secret and validate it here, mirroring the DECIDE_BILLING_ANALYTICS_TOKEN+ # check in posthog/tasks/usage_report.py (a duckgres-side change, out of scope for this PR).+ #+ # Local import: this module loads during django.setup() (via posthog.models), so keep the+ # ClickHouse client off that path.+ from posthog.clickhouse.client import sync_execute # noqa: PLC0415++ rows = sync_execute(+ """+ SELECT sum(JSONExtractFloat(properties, 'cpu_seconds'))+ FROM events+ WHERE team_id = %(team_id)s+ AND event = 'managed warehouse compute usage'+ AND timestamp >= %(start)s+ AND timestamp < %(end)s+ """,+ {"team_id": team_id, "start": start, "end": end},+ team_id=team_id,+ )+ return (rows and rows[0][0]) or 0.0+class ProductIntentSerializer(serializers.Serializer):"""@@ -232,6 +274,38 @@ class ProductIntent(UUIDTModel, RootTeamMixin):# At least one workflow needs to be active (not just drafted)return HogFlow.objects.filter(team=self.team, status=HogFlow.State.ACTIVE).exists()+ def has_activated_managed_warehouse(self) -> bool:+ # Provisioning is the intent; genuine usage is compute crossing the threshold within+ # 30 days of the intent (mirrors has_activated_data_warehouse's window).+ window_end = self.created_at + timedelta(days=MANAGED_WAREHOUSE_ACTIVATION_WINDOW_DAYS)++ # Unlike the other (Postgres-backed) checks, this one reads ClickHouse. Gate the query+ # behind cheap Postgres checks so it only fires when it could change the answer:+ # 1. once the 30-day window has closed, activation is permanently impossible, and+ # 2. a team that never emitted the compute-usage heartbeat cannot have any usage.+ if datetime.now(tz=UTC) > window_end:+ return False+ if not EventDefinition.objects.filter(team=self.team, name="managed warehouse compute usage").exists():+ return False++ # register() calls check_and_update_activation() synchronously on every intent PATCH, so+ # without this an authenticated member could drive an unbounded ClickHouse query rate by+ # re-hitting add_product_intent. Debounce the query per team via a short cache TTL; on a+ # miss we skip and report not-activated for now — the daily calculate_product_activation+ # task (and the next call after the TTL) will run the real check. Fail open on cache errors.+ debounce_key = f"managed_warehouse_activation_checked:{self.team_id}"+ try:+ should_query = cache.add(debounce_key, "1", timeout=MANAGED_WAREHOUSE_ACTIVATION_CHECK_TTL_SECONDS)+ except Exception as e:+ logger.warning("managed_warehouse_activation_debounce_cache_failure", team_id=self.team_id, exc_info=True)+ capture_exception(e)+ should_query = True+ if not should_query:+ return False++ usage = get_managed_warehouse_compute_usage(self.team_id, self.created_at, window_end)+ return usage >= MANAGED_WAREHOUSE_ACTIVATION_CPU_SECONDS+def check_and_update_activation(self, skip_reporting: bool = False) -> bool:# If the intent is already activated, we don't need to check againif self.activated_at:@@ -341,6 +415,7 @@ ACTIVATION_CHECKS: dict[str, Callable[[ProductIntent], bool]] = {"llm_analytics": ProductIntent.has_activated_llm_analytics,"mcp_analytics": ProductIntent.has_activated_mcp_analytics,"workflows": ProductIntent.has_activated_workflows,+ "managed_warehouse": ProductIntent.has_activated_managed_warehouse,}ACTIVATION_CHECK_PRODUCT_KEYS: frozenset[str] = frozenset(ACTIVATION_CHECKS)diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.pyindex 044f7f89bd20..af7d9542b9cc 100644--- a/posthog/models/test/test_product_intent.py+++ b/posthog/models/test/test_product_intent.py@@ -13,6 +13,7 @@ from posthog.schema import ProductIntentContext, ProductKeyfrom posthog.models.file_system.user_product_list import UserProductListfrom posthog.models.product_intent.product_intent import (+ MANAGED_WAREHOUSE_ACTIVATION_CPU_SECONDS,ProductIntent,_fetch_product_intents,_team_product_intents_cache_key,@@ -39,6 +40,9 @@ class TestProductIntent(BaseTest):# Joining the org seeds the fixed default product set; these tests assert on# product-intent-driven rows, so start from a clean slate.UserProductList.objects.filter(user=self.user, team=self.team).delete()+ # The managed warehouse activation check debounces via the cache; clear it so the+ # per-team key from one test can't suppress the ClickHouse check in the next.+ cache.clear()self.product_intent = ProductIntent.objects.create(team=self.team, product_type=ProductKey.DATA_WAREHOUSE)def test_str_representation(self):@@ -375,6 +379,97 @@ class TestProductIntent(BaseTest):team=self.team,)+ @freeze_time("2024-01-01T12:00:00Z")+ @patch("posthog.models.product_intent.product_intent.get_managed_warehouse_compute_usage", return_value=0.0)+ @patch("posthog.event_usage.report_user_action")+ def test_register_managed_warehouse_intent(self, mock_report_user_action, mock_compute_usage):+ # Managed warehouse is a distinct product from data_warehouse imports. Provisioning is the+ # intent; activation requires compute usage above a threshold within 30 days, which cannot+ # be true at intent time (usage only accrues after provisioning), so it never auto-activates here.+ ProductIntent.register(+ team=self.team,+ product_type=ProductKey.MANAGED_WAREHOUSE,+ context=ProductIntentContext.MANAGED_WAREHOUSE_PROVISIONED,+ user=self.user,+ )++ intent = ProductIntent.objects.filter(team=self.team, product_type=ProductKey.MANAGED_WAREHOUSE).first()+ assert intent is not None+ assert intent.contexts == {ProductIntentContext.MANAGED_WAREHOUSE_PROVISIONED: 1}+ assert intent.activated_at is None+ assert intent.check_and_update_activation() is False++ mock_report_user_action.assert_called_once_with(+ self.user,+ "user showed product intent",+ {+ "product_key": ProductKey.MANAGED_WAREHOUSE,+ "$set_once": {},+ "intent_context": ProductIntentContext.MANAGED_WAREHOUSE_PROVISIONED,+ "is_first_intent_for_product": True,+ "intent_created_at": datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC),+ "intent_updated_at": datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC),+ "realm": get_instance_realm(),+ },+ team=self.team,+ )++ @parameterized.expand(+ [+ ("zero", 0.0, False),+ ("below_threshold", float(MANAGED_WAREHOUSE_ACTIVATION_CPU_SECONDS - 1), False),+ ("at_threshold", float(MANAGED_WAREHOUSE_ACTIVATION_CPU_SECONDS), True),+ ("above_threshold", float(MANAGED_WAREHOUSE_ACTIVATION_CPU_SECONDS * 2), True),+ ]+ )+ @patch("posthog.models.product_intent.product_intent.get_managed_warehouse_compute_usage")+ def test_has_activated_managed_warehouse(self, _name, usage, expected, mock_compute_usage):+ mock_compute_usage.return_value = usage+ EventDefinition.objects.create(team=self.team, name="managed warehouse compute usage")+ intent = ProductIntent.objects.create(team=self.team, product_type=ProductKey.MANAGED_WAREHOUSE)+ assert intent.has_activated_managed_warehouse() is expected++ @freeze_time("2024-01-01T12:00:00Z")+ @patch("posthog.models.product_intent.product_intent.get_managed_warehouse_compute_usage", return_value=0.0)+ def test_managed_warehouse_activation_uses_30_day_window(self, mock_compute_usage):+ # Usage is only counted within 30 days of the intent, so the compute lookup must be+ # bounded to [created_at, created_at + 30 days).+ EventDefinition.objects.create(team=self.team, name="managed warehouse compute usage")+ intent = ProductIntent.objects.create(team=self.team, product_type=ProductKey.MANAGED_WAREHOUSE)+ assert intent.has_activated_managed_warehouse() is False+ mock_compute_usage.assert_called_once_with(+ self.team.id,+ datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC),+ datetime(2024, 1, 31, 12, 0, 0, tzinfo=UTC),+ )++ @patch("posthog.models.product_intent.product_intent.get_managed_warehouse_compute_usage")+ def test_managed_warehouse_activation_skips_clickhouse_without_usage_event(self, mock_compute_usage):+ # A team that never emitted the compute-usage heartbeat must not trigger a ClickHouse query.+ intent = ProductIntent.objects.create(team=self.team, product_type=ProductKey.MANAGED_WAREHOUSE)+ assert intent.has_activated_managed_warehouse() is False+ mock_compute_usage.assert_not_called()++ @patch("posthog.models.product_intent.product_intent.get_managed_warehouse_compute_usage")+ def test_managed_warehouse_activation_skips_clickhouse_after_window(self, mock_compute_usage):+ # Once the 30-day window has closed, activation is impossible, so no ClickHouse query runs.+ EventDefinition.objects.create(team=self.team, name="managed warehouse compute usage")+ with freeze_time("2024-01-01T12:00:00Z"):+ intent = ProductIntent.objects.create(team=self.team, product_type=ProductKey.MANAGED_WAREHOUSE)+ with freeze_time("2024-03-01T12:00:00Z"):+ assert intent.has_activated_managed_warehouse() is False+ mock_compute_usage.assert_not_called()++ @patch("posthog.models.product_intent.product_intent.get_managed_warehouse_compute_usage", return_value=0.0)+ def test_managed_warehouse_activation_query_is_debounced(self, mock_compute_usage):+ # register() runs this check synchronously on every intent PATCH, so repeated calls must+ # not each hit ClickHouse — the per-team cache TTL collapses them to one query.+ EventDefinition.objects.create(team=self.team, name="managed warehouse compute usage")+ intent = ProductIntent.objects.create(team=self.team, product_type=ProductKey.MANAGED_WAREHOUSE)+ assert intent.has_activated_managed_warehouse() is False+ assert intent.has_activated_managed_warehouse() is False+ mock_compute_usage.assert_called_once()+def test_has_activated_product_analytics_with_all_criteria(self):self.product_intent.product_type = ProductKey.PRODUCT_ANALYTICSself.product_intent.save()diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex cb16e913ec1f..8c9af6b1cbda 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3267,6 +3267,7 @@ class ProductIntentContext(StrEnum):SELECTED_CONNECTOR = "selected connector"SQL_EDITOR_EMPTY_STATE = "sql editor empty state"DATA_WAREHOUSE_SOURCES_TABLE = "data warehouse sources table"+ MANAGED_WAREHOUSE_PROVISIONED = "managed warehouse provisioned"EXPERIMENT_CREATED = "experiment created"EXPERIMENT_ANALYZED = "experiment analyzed"EXPERIMENT_VIEW_RECORDINGS = "experiment view recordings"@@ -3400,6 +3401,7 @@ class ProductKey(StrEnum):LLM_EVALUATIONS = "llm_evaluations"LLM_PROMPTS = "llm_prompts"LOGS = "logs"+ MANAGED_WAREHOUSE = "managed_warehouse"MARKETING_ANALYTICS = "marketing_analytics"MAX = "max"MCP_ANALYTICS = "mcp_analytics"