: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(workflows): suggest account properties as output variables (#69489)
Arthur Moreira de Deuscc6440bff1dd
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex 31afb8a0135f..74774e108746 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -76,6 +76,10 @@ registerAsyncFunction('postHogGetAccount', {CSM: [{ user_id: 1, email: '[email protected]' }],'Account executive': [{ user_id: 2, email: '[email protected]' }],},+ custom_properties: {+ Plan: 'enterprise',+ 'MRR (net)': 1234,+ },},}},diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.mdindex 612d76fb49bb..dd21416d986d 100644--- a/products/customer_analytics/backend/COMPROMISES.md+++ b/products/customer_analytics/backend/COMPROMISES.md@@ -62,6 +62,22 @@ Cutover checklist — when done, the sync and this section are deleted:- [ ] Delete `sync_from_account_properties` + call sites; strip the three role keys from`AccountProperties`+## External account `custom_properties` payload++- **Every definition is emitted, unbounded.** `_to_external_account` includes every team+ custom property definition keyed by name (`null` when unset) so workflow result paths are+ deterministic. The hogflow executor caps all workflow variables at 5 KB of JSON combined and+ the Get account node's default `account` variable stores the whole response body, so a team+ with enough definitions (roughly 100–150 at typical name lengths, fewer with long names or+ populated values) makes every Get account step throw and drop its variables — even in+ workflows that never touch custom properties. If this bites: stop emitting unset definitions+ as `null`, or drop the whole-body default variable in favor of path-scoped ones.+- **Output variable suggestions read one page.** The workflow editor's suggestion chips fetch+ custom property and relationship definitions without pagination (default page size 100), so+ definitions past the first page silently never appear as suggestions — the value still exists+ in the payload and can be mapped by hand. Follow `next` pages in+ `getOutputMappingSuggestions` (workflows frontend registry) if teams that large show up.+## Tech debt- **Account property writes have no single choke point.** `Account._properties` is mutated from fourdiff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 4a49d7a56389..9b2f2a7800ae 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -16,6 +16,7 @@ Do NOT:"""from collections.abc import Iterable+from datetime import datetimefrom typing import TYPE_CHECKING, Any, Optional, castfrom uuid import UUID@@ -256,6 +257,10 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:``properties`` is the exact ``model_dump(mode="json")`` of the validatedpydantic properties and ``tags`` the sorted tag names — byte-identical towhat the CDP worker consumed before this moved behind the facade.++ ``custom_properties`` includes every team definition keyed by name, with the+ account's active value (scalar) or ``None`` when unset, so workflow result+ paths are deterministic regardless of whether the property has been set."""relationships: dict[str, list[dict]] = {}for relationship in (@@ -268,6 +273,19 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:relationships.setdefault(relationship.definition.name, []).append({"user_id": relationship.user.id, "email": relationship.user.email})++ definitions = list(CustomPropertyDefinition.objects.for_team(account.team_id).values("id", "name"))+ active_values = {+ row.definition_id: row+ for row in _custom_property_values_logic.list_active_custom_property_values(+ team_id=account.team_id, account_id=account.id+ )+ }+ custom_properties: dict[str, float | bool | str | None] = {+ defn["name"]: _scalar_value(active_values[defn["id"]]) if defn["id"] in active_values else None+ for defn in definitions+ }+return contracts.ExternalAccount(id=str(account.id),external_id=account.external_id,@@ -275,9 +293,20 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:properties=account.properties.model_dump(mode="json"),tags=sorted(account.tagged_items.values_list("tag__name", flat=True)),relationships=relationships,+ custom_properties=custom_properties,)+def _scalar_value(row: "CustomPropertyValue") -> float | bool | str | None:+ """Return the row's value as a JSON-safe scalar; datetimes become ISO strings."""+ v = _custom_property_values_logic.value_of(row)+ if isinstance(v, datetime):+ return v.isoformat()+ if isinstance(v, float | bool | str):+ return v+ return None++def _get_external_account_by_external_id(team_id: int, external_id: str) -> Account | None:try:return Account.objects.for_team(team_id).select_related("team").get(external_id=external_id)diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 2f15f52529cf..28bfbbba641b 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -135,6 +135,11 @@ class ExternalAccount:consumes stays byte-identical to the pre-facade response — a validatedpydantic pass-through, not a re-typed projection. ``id`` is the stringifiedUUID, matching the wire shape.++ ``custom_properties`` contains every team-defined custom property definition+ keyed by definition name, with the account's current scalar value (or ``None``+ when unset). Every definition is present so result paths are deterministic even+ when a property hasn't been set on this account yet."""id: str@@ -143,6 +148,7 @@ class ExternalAccount:properties: dicttags: list[str] = field(default_factory=list)relationships: dict[str, list[dict]] = field(default_factory=dict)+ custom_properties: dict[str, float | bool | str | None] = field(default_factory=dict)class ExternalAccountUpdateError(Enum):diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex fb7a504399b4..2c2237df6d4a 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -123,6 +123,7 @@ def _external_account_body(account: contracts.ExternalAccount) -> dict[str, Any]"properties": account.properties,"tags": account.tags,"relationships": account.relationships,+ "custom_properties": account.custom_properties,}diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex 0f246c8f8cb2..d9170589f3eb 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -1,3 +1,4 @@+from datetime import UTC, datetimefrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -125,6 +126,32 @@ class TestExternalAccountAPI(APIBaseTest):{"CSM": [{"user_id": self.user.id, "email": self.user.email}]},)+ def test_get_account_returns_custom_properties(self):+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=DisplayType.TEXT)+ create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)+ renewal = create_custom_property_definition(+ team_id=self.team.id, name="Renewal", display_type=DisplayType.DATETIME+ )+ CustomPropertyValue.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ account=self.account,+ definition=plan,+ value_str="enterprise",+ )+ CustomPropertyValue.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ account=self.account,+ definition=renewal,+ value_datetime=datetime(2026, 7, 1, 12, 0, tzinfo=UTC),+ )++ response = self._get()+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ response.json()["custom_properties"],+ {"Plan": "enterprise", "Seats": None, "Renewal": "2026-07-01T12:00:00+00:00"},+ )+def test_does_not_leak_accounts_from_other_team(self):other_team = Team.objects.create(organization=self.organization, name="Other")other_team.secret_api_token = generate_random_token_secret()diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsxindex 99b79ab98dab..ac9a74666ce8 100644--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx@@ -141,10 +141,17 @@ export type HogFlowEditorActionMetrics = {filtered: number}+export type OutputMappingSuggestion = {+ key: string+ result_path: string+ label: string+}+export type CreateActionType = Pick<HogFlowAction, 'type' | 'config' | 'name' | 'description'> & {branchEdges?: numberoutput_variable?: HogFlowAction['output_variable']getDefaultInputs?: () => Record<string, CyclotronInputType> | undefined+ getOutputMappingSuggestions?: () => Promise<OutputMappingSuggestion[]>}export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsxindex 0f31ec7f8861..d087dc6c4b0f 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx@@ -33,9 +33,8 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {const { selectedNode, workflow, categories, categoriesLoading } = useValues(hogFlowEditorLogic)const { setWorkflowAction, setMode } = useActions(hogFlowEditorLogic)const { logicProps } = useValues(workflowLogic)- const { mappings, pendingPath, testLoading, testError, testResultData, shakePickButton } = useValues(- hogFlowOutputMappingLogic(logicProps)- )+ const { mappings, pendingPath, testLoading, testError, testResultData, shakePickButton, pendingSuggestions } =+ useValues(hogFlowOutputMappingLogic(logicProps))const {setSelectedActionId,setMappings,@@ -46,6 +45,7 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {assignPendingPathToMapping,cancelPendingPath,runOutputTest,+ applySuggestion,} = useActions(hogFlowOutputMappingLogic(logicProps))useEffect(() => {@@ -237,6 +237,24 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {</LemonField.Pure></div>))}+ {pendingSuggestions.length > 0 && (+ <div className="w-full">+ <p className="text-xs text-secondary mb-1">Suggested</p>+ <div className="flex flex-wrap gap-1">+ {pendingSuggestions.map((suggestion) => (+ <LemonButton+ key={suggestion.key}+ size="xsmall"+ type="secondary"+ icon={<IconPlus />}+ onClick={() => applySuggestion(suggestion)}+ >+ {suggestion.label}+ </LemonButton>+ ))}+ </div>+ </div>+ )}<div className="flex gap-2 w-full"><LemonButtonicon={<IconPlus />}diff --git a/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.tsindex a20244df6d20..d24890b26753 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.ts@@ -1,9 +1,12 @@import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'import api from 'lib/api'import { WorkflowLogicProps, sanitizeWorkflow, workflowLogic } from '../../workflowLogic'+import { OutputMappingSuggestion } from '../hogFlowEditorLogic'import { hogFlowEditorLogic } from '../hogFlowEditorLogic'+import { getRegisteredActionNodeCategories } from '../registry/actions/actionNodeRegistry'import type { HogflowTestResult } from '../steps/types'import type { HogFlowAction } from '../types'import type { hogFlowOutputMappingLogicType } from './hogFlowOutputMappingLogicType'@@ -63,8 +66,42 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([setTestError: (error: string | null) => ({ error }),setTestResultData: (data: unknown | null) => ({ data }),setShakePickButton: (shake: boolean) => ({ shake }),+ applySuggestion: (suggestion: OutputMappingSuggestion) => ({ suggestion }),}),+ loaders(({ values }) => ({+ suggestions: {+ __default: [] as OutputMappingSuggestion[],+ loadSuggestions: async (_, breakpoint): Promise<OutputMappingSuggestion[]> => {+ const { selectedNode } = values+ if (!selectedNode) {+ return []+ }+ const config = selectedNode.data?.config+ const templateId = config && 'template_id' in config ? config.template_id : undefined+ if (!templateId) {+ return []+ }+ const nodeDef = getRegisteredActionNodeCategories()+ .flatMap((c) => c.nodes)+ .find((n) => 'template_id' in n.config && n.config.template_id === templateId)+ if (!nodeDef?.getOutputMappingSuggestions) {+ return []+ }+ let suggestions: OutputMappingSuggestion[]+ try {+ suggestions = await nodeDef.getOutputMappingSuggestions()+ } catch {+ suggestions = []+ }+ breakpoint()+ return suggestions+ },+ },+ })),reducers({+ suggestions: {+ setSelectedActionId: () => [],+ },selectedActionId: [null as string | null,{@@ -125,6 +162,14 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([}),selectors({selectedAction: [(s) => [s.selectedNode], (selectedNode) => selectedNode?.data ?? null],+ pendingSuggestions: [+ (s) => [s.suggestions, s.mappings],+ (suggestions, mappings): OutputMappingSuggestion[] => {+ const usedResultPaths = new Set(mappings.map((m) => m.result_path).filter(Boolean))+ const usedKeys = new Set(mappings.map((m) => m.key).filter(Boolean))+ return suggestions.filter((s) => !usedResultPaths.has(s.result_path) && !usedKeys.has(s.key))+ },+ ],}),listeners(({ actions, values, props }) => {const persistMappings = (newMappings: OutputMapping[]): void => {@@ -151,6 +196,7 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([const selectedNode = values.selectedNodeif (selectedNode) {actions.initMappings(normalizeOutputVariable(selectedNode.data.output_variable))+ actions.loadSuggestions({})}},setMappings: ({ mappings }) => {@@ -189,6 +235,21 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([setTimeout(() => actions.setShakePickButton(false), 1000)}},+ applySuggestion: ({ suggestion }) => {+ const newMappings = [...values.mappings, { key: suggestion.key, result_path: suggestion.result_path }]+ actions.setMappings(newMappings)++ const { workflow } = values+ const existingVars = workflow.variables ?? []+ if (!existingVars.some((v) => v.key === suggestion.key)) {+ workflowLogic(props).actions.setWorkflowInfo({+ variables: [+ ...existingVars,+ { key: suggestion.key, label: suggestion.label, type: 'string' as const, default: '' },+ ],+ })+ }+ },runOutputTest: async () => {const { selectedNode, workflow, hogFunctionTemplatesById } = valuesif (!selectedNode) {diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.tsindex e8eff545f124..cc3db6f78257 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts@@ -3,7 +3,12 @@ import { FEATURE_FLAGS } from 'lib/constants'import { GroupType, GroupTypeIndex } from '~/types'import { getRegisteredActionNodeCategories } from './actionNodeRegistry'-import { buildAccountExternalIdInputs } from './customer_analytics'+import {+ buildAccountExternalIdInputs,+ buildAccountOutputSuggestions,+ customPropertyResultPath,+ slugifyName,+} from './customer_analytics'const groupTypesMap = (...entries: [GroupTypeIndex, string][]): Map<GroupTypeIndex, GroupType> =>new Map(entries.map(([index, groupType]) => [index, { group_type: groupType, group_type_index: index }]))@@ -89,6 +94,47 @@ describe('customer analytics action registry', () => {})+ describe('slugifyName', () => {+ it.each([+ ['Plan', 'plan'],+ ['MRR (net)', 'mrr_net'],+ ['ARR (net)', 'arr_net'],+ ['my_property', 'my_property'],+ [' spaces ', 'spaces'],+ ['a--b', 'a_b'],+ ])('slugifies %s → %s', (input, expected) => {+ expect(slugifyName(input)).toBe(expected)+ })+ })++ describe('customPropertyResultPath', () => {+ it.each([+ ['Plan', 'custom_properties.Plan'],+ ['my_prop', 'custom_properties.my_prop'],+ ['ARR123', 'custom_properties.ARR123'],+ ['MRR (net)', 'custom_properties["MRR (net)"]'],+ ['has space', 'custom_properties["has space"]'],+ ['with"quote', 'custom_properties["with\\"quote"]'],+ ])('builds result path for %s → %s', (name, expected) => {+ expect(customPropertyResultPath(name)).toBe(expected)+ })+ })++ describe('buildAccountOutputSuggestions', () => {+ it('namespaces relationships and dedupes colliding keys', () => {+ const suggestions = buildAccountOutputSuggestions(['Plan', 'MRR (net)', 'MRR net'], ['Plan', 'CSM'])+ expect(suggestions.map((s) => s.key)).toEqual([+ 'account_plan',+ 'account_mrr_net',+ 'account_relationship_plan',+ 'account_relationship_csm',+ ])+ expect(suggestions.find((s) => s.key === 'account_relationship_csm')?.result_path).toBe(+ 'relationships["CSM"]'+ )+ })+ })+describe('buildAccountExternalIdInputs', () => {it('builds a name-based group key expression from the account group type index', () => {const inputs = buildAccountExternalIdInputs(2, groupTypesMap([0, 'project'], [2, 'organization']))diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.tsindex 75edfbf92fdd..f874f8bdef7c 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts@@ -1,9 +1,15 @@import { FEATURE_FLAGS } from 'lib/constants'+import { projectLogic } from 'scenes/projectLogic'import { teamLogic } from 'scenes/teamLogic'import { groupsModel } from '~/models/groupsModel'import { GroupType, GroupTypeIndex } from '~/types'+import {+ accountRelationshipDefinitionsList,+ customPropertyDefinitionsList,+} from 'products/customer_analytics/frontend/generated/api'+import { OutputMappingSuggestion } from 'products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic'import { registerActionNodeCategory } from 'products/workflows/frontend/Workflows/hogflows/registry/actions/actionNodeRegistry'import { CyclotronInputType } from 'products/workflows/frontend/Workflows/hogflows/steps/types'@@ -31,6 +37,63 @@ const getAccountExternalIdDefaultInputs = (): Record<string, CyclotronInputType>groupsModel.findMounted()?.values.groupTypes ?? new Map())+/** Slugify a definition name to a safe variable key suffix: lowercase, non-alphanumeric → `_`, collapse and trim. */+export const slugifyName = (name: string): string =>+ name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '')++/** Build a lodash-get-compatible result_path for a custom property name.+ * Names matching /^[A-Za-z0-9_]+$/ use dot notation; others use bracket notation with `"` escaped. */+export const customPropertyResultPath = (name: string): string => {+ if (/^[A-Za-z0-9_]+$/.test(name)) {+ return `custom_properties.${name}`+ }+ const escaped = name.replace(/"/g, '\\"')+ return `custom_properties["${escaped}"]`+}++/** Assemble suggestions from definition names, deduped by variable key (first wins on slug collisions). */+export const buildAccountOutputSuggestions = (+ customPropertyNames: string[],+ relationshipNames: string[]+): OutputMappingSuggestion[] => {+ const suggestions = [+ ...customPropertyNames.map((name) => ({+ key: `account_${slugifyName(name)}`,+ result_path: customPropertyResultPath(name),+ label: name,+ })),+ ...relationshipNames.map((name) => ({+ key: `account_relationship_${slugifyName(name)}`,+ result_path: `relationships["${name.replace(/"/g, '\\"')}"]`,+ label: `${name} (relationship)`,+ })),+ ]+ const seenKeys = new Set<string>()+ return suggestions.filter((s) => !seenKeys.has(s.key) && !!seenKeys.add(s.key))+}++const getOutputMappingSuggestions = async (): Promise<OutputMappingSuggestion[]> => {+ const projectId = String(projectLogic.findMounted()?.values.currentProjectId ?? '')+ if (!projectId) {+ return []+ }+ try {+ const [customPropsResponse, relDefsResponse] = await Promise.all([+ customPropertyDefinitionsList(projectId),+ accountRelationshipDefinitionsList(projectId),+ ])+ return buildAccountOutputSuggestions(+ (customPropsResponse.results ?? []).map((defn) => defn.name),+ (relDefsResponse.results ?? []).map((defn) => defn.name)+ )+ } catch {+ return []+ }+}+registerActionNodeCategory({label: 'Customer analytics',featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,@@ -41,6 +104,7 @@ registerActionNodeCategory({description: 'Fetch a Customer analytics account into a workflow variable.',config: { template_id: 'template-posthog-get-account', inputs: {} },getDefaultInputs: getAccountExternalIdDefaultInputs,+ getOutputMappingSuggestions,output_variable: [{ key: 'account', result_path: null, label: 'Account' },{ key: 'account_relationships', result_path: 'relationships', label: 'Relationships' },