Skip to content

: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.

feat(customer-analytics): clear workflow properties (#92855)

Arthur Moreira de Deusd749319668a1
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.ts
index 9cf149586867..943094f83e36 100644
--- a/nodejs/src/cdp/async-functions/customer_analytics.ts
+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts
@@ -9,6 +9,32 @@ import { callInternalApi } from './internal-api-call'
import { getTeamWithSecretToken } from './secret-api-token'
const ACCOUNT_ACTIONS = 'account workflow actions'
+const CLEAR_PROPERTY_MARKER = '__posthog_clear_property'
+
+function isClearPropertyMarker(value: unknown): boolean {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ !Array.isArray(value) &&
+ Object.keys(value).length === 1 &&
+ (value as Record<string, unknown>)[CLEAR_PROPERTY_MARKER] === true
+ )
+}
+
+function normalizeAccountProperties(properties: Record<string, unknown>): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(properties).map(([definitionId, value]) => {
+ if (value === null) {
+ throw new Error(
+ `[HogFunction] - postHogSetAccountProperties received null for property '${definitionId}'. ` +
+ 'Use Clear property in the workflow editor, or make the template return a value.'
+ )
+ }
+
+ return [definitionId, isClearPropertyMarker(value) ? null : value]
+ })
+ )
+}
/**
* Calls the JWT-only internal account routes (products/customer_analytics/backend/
@@ -188,11 +214,13 @@ registerAsyncFunction('postHogSetAccountProperties', {
throw new Error("[HogFunction] - postHogSetAccountProperties call missing 'external_id' property")
}
+ const normalizedProperties = normalizeAccountProperties(properties)
+
if (context.customerAnalyticsAccountsJwt.enabled) {
await callInternalAccountApi(context, result, externalId, {
method: 'PATCH',
subpath: '/custom_property_values',
- body: JSON.stringify({ external_id: externalId, properties }),
+ body: JSON.stringify({ external_id: externalId, properties: normalizedProperties }),
extraHeaders: hogFlowHeaders(context),
})
return
@@ -211,7 +239,7 @@ registerAsyncFunction('postHogSetAccountProperties', {
type: 'fetch',
url: `${context.siteUrl}/api/customer_analytics/external/account/custom_property_values`,
method: 'PATCH',
- body: JSON.stringify({ external_id: externalId, properties }),
+ body: JSON.stringify({ external_id: externalId, properties: normalizedProperties }),
headers,
})
},
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index fe5683332f33..ac07708f68a9 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -1071,13 +1071,13 @@ describe('Hog Executor', () => {
expect(claims.external_id).toEqual('acme-1')
})
- it('postHogSetAccountProperties targets the custom_property_values route', async () => {
+ it('postHogSetAccountProperties sends an explicit property clear as API null', async () => {
const fetchSpy = jest
.spyOn(requestModule, 'internalFetch')
.mockResolvedValue(mockInternalResponse(200, { ok: true }))
mockExecHogForAsyncFunction('postHogSetAccountProperties', [
- { external_id: 'acme-1', properties: { 'def-1': 'gold' } },
+ { external_id: 'acme-1', properties: { 'def-1': { __posthog_clear_property: true } } },
])
await executor.execute(createAccountInvocation())
@@ -1086,7 +1086,7 @@ describe('Hog Executor', () => {
`${hub.INTERNAL_API_BASE_URL}/api/projects/1/internal/customer_analytics/account/custom_property_values`
)
expect(options.method).toEqual('PATCH')
- expect(options.body).toEqual(JSON.stringify({ external_id: 'acme-1', properties: { 'def-1': 'gold' } }))
+ expect(options.body).toEqual(JSON.stringify({ external_id: 'acme-1', properties: { 'def-1': null } }))
})
it('postHogCreateAccount posts the claimed external_id with workflow attribution', async () => {
@@ -1194,6 +1194,21 @@ describe('Hog Executor', () => {
expect(captureExceptionSpy).not.toHaveBeenCalled()
})
+ it('rejects a null custom property value rather than queueing a clear', async () => {
+ disableAccountJwt()
+ const getTeamSpy = jest.spyOn(hub.teamManager, 'getTeam')
+
+ mockExecHogForAsyncFunction('postHogSetAccountProperties', [
+ { external_id: 'acme-1', properties: { 'def-1': null } },
+ ])
+ const result = await executor.execute(createAccountInvocation())
+
+ expect(result.error).toContain("received null for property 'def-1'")
+ expect(result.error).toContain('Use Clear property in the workflow editor')
+ expect(result.invocation.queueParameters).toBeUndefined()
+ expect(getTeamSpy).not.toHaveBeenCalled()
+ })
+
it('postHogUpdateAccount queues a PATCH with external_id merged into the body', async () => {
disableAccountJwt()
jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts
index 36022060795a..6e80528f6e22 100644
--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts
+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts
@@ -150,6 +150,37 @@ describe('posthog customer analytics account templates', () => {
})
})
+ describe('update account property queued fetch body', () => {
+ const tester = new TemplateTester(updateAccountPropertyTemplate)
+
+ beforeEach(async () => {
+ await tester.beforeEach()
+ })
+
+ it('sends an explicit property clear as API null', async () => {
+ const response = await tester.invoke({
+ external_id: 'acme-1',
+ properties: { '0197f9f0-0000-0000-0000-000000000000': { __posthog_clear_property: true } },
+ })
+
+ expect(response.error).toBeUndefined()
+ expect(response.finished).toBe(false)
+
+ const body = parseJSON((response.invocation.queueParameters as any).body)
+ expect(body.properties).toEqual({ '0197f9f0-0000-0000-0000-000000000000': null })
+ })
+
+ it('rejects a property template that resolves to null', async () => {
+ const response = await tester.invoke({
+ external_id: 'acme-1',
+ properties: { '0197f9f0-0000-0000-0000-000000000000': '{event.properties.plan}' },
+ })
+
+ expect(response.error).toContain("received null for property '0197f9f0-0000-0000-0000-000000000000'")
+ expect(response.invocation.queueParameters).toBeUndefined()
+ })
+ })
+
describe('update account relationships queued fetch body', () => {
const tester = new TemplateTester(updateAccountRelationshipsTemplate)
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts
index c961749a195e..1ba0f9c7e0c1 100644
--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts
+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account-property.template.ts
@@ -8,7 +8,7 @@ export const template: HogFunctionTemplate = {
type: 'destination',
id: 'template-posthog-update-account-property',
name: 'Update account property',
- description: 'Set custom property values on a Customer analytics account.',
+ description: 'Set or clear custom property values on a Customer analytics account.',
icon_url: '/static/posthog-icon.svg',
category: ['Custom'],
code_language: 'hog',
@@ -48,10 +48,10 @@ return response.body
{
key: 'properties',
type: 'customer_analytics_account_properties',
- label: 'Properties to set',
+ label: 'Properties to update',
secret: false,
required: true,
- description: 'Custom property values to set on the account.',
+ description: 'Custom property values to set or clear. Omitted properties are unchanged.',
},
],
}
diff --git a/nodejs/tests/fixtures/hog-bytecode/6d5370f22a05be2a02c10308fb6d4933decc8771d7ee26d006104706163b3560.json b/nodejs/tests/fixtures/hog-bytecode/6d5370f22a05be2a02c10308fb6d4933decc8771d7ee26d006104706163b3560.json
new file mode 100644
index 000000000000..2c5c53a2ba49
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/6d5370f22a05be2a02c10308fb6d4933decc8771d7ee26d006104706163b3560.json
@@ -0,0 +1 @@
+["_H",1,32,"plan",32,"properties",32,"event",1,3,38]
diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.py
index 1f5a05f17814..436b8151e131 100644
--- a/posthog/cdp/test/test_validation.py
+++ b/posthog/cdp/test/test_validation.py
@@ -1179,12 +1179,23 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT
def test_customer_analytics_account_properties_compiles_dict_values_to_bytecode(self):
# Without the opt-in into transpilation, the dict values ship without bytecode and the
# Node runtime sets the literal placeholder string instead of the interpolated value.
+ clear_marker = {"__posthog_clear_property": True}
inputs_schema = [{"key": "properties", "type": "customer_analytics_account_properties", "required": True}]
- inputs = {"properties": {"value": {"Plan tier": "{event.properties.plan}", "MRR": "5000"}}}
+ inputs = {
+ "properties": {
+ "value": {
+ "Plan tier": "{event.properties.plan}",
+ "MRR": "5000",
+ "Property to clear": clear_marker,
+ }
+ }
+ }
validated = validate_inputs(inputs_schema, inputs)
assert validated["properties"].get("bytecode") is not None
+ assert validated["properties"]["value"]["Property to clear"] == clear_marker
+ assert validated["properties"]["bytecode"]["Property to clear"] == clear_marker
def test_customer_analytics_account_relationships_validates_assignment_dict(self):
# Guards the type's registration in InputsSchemaItemSerializer's ChoiceField —
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 095c70b0404a..3f514d2e7f8d 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -793,12 +793,13 @@ def set_external_account_custom_properties(
created_by_id: int | None = None,
workflow_id: str | None = None,
) -> contracts.ExternalAccountCustomPropertiesResult:
- """Set custom property values on an account by definition id, for the external API.
+ """Set or clear custom property values on an account by definition id, for the external API.
Resolves the account by external id, then applies every ``{definition_id: value}`` pair
- transactionally — a bad value or unknown definition rolls the whole batch back. Returns a result
- the view maps to the exact HTTP status/body: account not found, unknown definition, invalid
- value, a concurrent-write conflict, a generic write failure, or success carrying the set values.
+ transactionally. A null value clears an active value. A bad value or unknown definition rolls
+ the whole batch back. Returns a result the view maps to the exact HTTP status/body: account not
+ found, unknown definition, invalid value, a concurrent-write conflict, a generic write failure,
+ or success carrying only the set values.
"""
account = _get_external_account_by_external_id(team_id, external_id)
if account is None:
@@ -3170,10 +3171,15 @@ def query_accounts_table(
for definition_id, window_days in history_windows.items():
history_filter |= Q(definition_id=definition_id, created_at__gte=now - timedelta(days=window_days))
history_filter |= Q(definition_id=definition_id, is_deleted=False)
+ active_values = CustomPropertyValue.objects.for_team(team_id).filter(
+ account_id=OuterRef("account_id"),
+ definition_id=OuterRef("definition_id"),
+ is_deleted=False,
+ )
history_point_count = 0
history_values = (
CustomPropertyValue.objects.for_team(team_id)
- .filter(history_filter, account_id__in=account_ids, value_num__isnull=False)
+ .filter(history_filter, Exists(active_values), account_id__in=account_ids, value_num__isnull=False)
.order_by("created_at", "id")
.iterator(chunk_size=2_000)
)
diff --git a/products/customer_analytics/backend/facade/hogql.py b/products/customer_analytics/backend/facade/hogql.py
index 63c9cc7a3352..aa8ab3347176 100644
--- a/products/customer_analytics/backend/facade/hogql.py
+++ b/products/customer_analytics/backend/facade/hogql.py
@@ -339,6 +339,7 @@ def _account_custom_properties_history_select(fields_accessed: dict[str, list[st
FROM system._account_custom_property_values_history AS cpv
WHERE isNotNull(cpv.value_num) AND (cpv.created_at >= now() - INTERVAL 180 DAY OR NOT cpv.is_deleted)
GROUP BY cpv.account_id, cpv.definition_id
+ HAVING countIf(NOT cpv.is_deleted) > 0
"""
)
select: list[ast.Expr] = [parse_expr("account_id AS account_id")]
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
index 8cc45ed4dd84..19d70dbbc5f0 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
@@ -18,6 +18,7 @@ from posthog.models.team import Team
from products.access_control.backend.facade.user_access_control import UserAccessControlError
from products.access_control.backend.models.access_control import AccessControl
+from products.customer_analytics.backend.facade import api
from products.customer_analytics.backend.hogql_queries.accounts_query_runner import AccountsQueryRunner
from products.customer_analytics.backend.logic import relationships as relationships_logic
from products.customer_analytics.backend.models import AccountRelationshipDefinition, CustomPropertyValue
@@ -550,6 +551,7 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
def test_custom_property_history_returns_ordered_writes_within_horizon(self):
account = create_account(team_id=self.team.id, name="A")
stale_account = create_account(team_id=self.team.id, name="Stale")
+ cleared_account = create_account(team_id=self.team.id, name="Cleared", external_id="cleared")
definition = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type="number")
text_definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
CustomPropertyValue.objects.unscoped().create(
@@ -568,11 +570,25 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
team_id=self.team.id, account=target, definition=definition, value_num=value, is_deleted=is_deleted
)
CustomPropertyValue.objects.unscoped().filter(id=row.id).update(created_at=written_at)
+ set_result = api.set_external_account_custom_properties(
+ self.team.id, "cleared", properties={str(definition.id): 15}
+ )
+ clear_result = api.set_external_account_custom_properties(
+ self.team.id, "cleared", properties={str(definition.id): None}
+ )
+ self.assertIsNone(set_result.error)
+ self.assertIsNone(clear_result.error)
+ self.assertTrue(
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .filter(account_id=cleared_account.id, definition_id=definition.id, is_deleted=True, value_num=15)
+ .exists()
+ )
runner = AccountsQueryRunner(
query=AccountsQuery(
select=[
"id",
+ f"accounts.custom_properties.values.`{definition.id}` AS numeric_value",
f"accounts.custom_properties_history.values.`{definition.id}` AS numeric_history",
f"accounts.custom_properties_history.values.`{text_definition.id}` AS text_history",
]
@@ -581,7 +597,7 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
user=self.user,
)
response = runner.calculate()
- self.assertEqual(len(response.results), 2)
+ self.assertEqual(len(response.results), 3)
id_idx = runner.columns.index("id")
rows_by_id = {str(row[id_idx]): row for row in response.results}
@@ -596,6 +612,10 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
stale_history = rows_by_id[str(stale_account.id)][runner.columns.index("numeric_history")]
self.assertEqual([point[1] for point in stale_history], [77.0])
+ cleared_row = rows_by_id[str(cleared_account.id)]
+ self.assertFalse(cleared_row[runner.columns.index("numeric_value")])
+ self.assertFalse(cleared_row[runner.columns.index("numeric_history")])
+
def test_numeric_custom_property_aggregates_in_metrics_mode(self):
# Overview tiles sum/avg a numeric custom property by casting its (string) value to a float.
definition = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type="number")
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
index 5e5aa13b5252..acb4a450318c 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
@@ -78,6 +78,7 @@ class TestAccountsTableQueryRunner(BaseTest):
def test_returns_requested_postgres_cells_with_typed_defaults(self) -> None:
empty_account = create_account(team_id=self.team.id, name="Empty")
+ cleared_account = create_account(team_id=self.team.id, name="Cleared", external_id="cleared")
account = create_account(
team_id=self.team.id,
name="Acme",
@@ -132,6 +133,19 @@ class TestAccountsTableQueryRunner(BaseTest):
now = timezone.now()
CustomPropertyValue.objects.unscoped().filter(id=old_value.id).update(created_at=now - timedelta(days=5))
CustomPropertyValue.objects.unscoped().filter(id=current_value.id).update(created_at=now - timedelta(days=1))
+ set_result = api.set_external_account_custom_properties(
+ self.team.id, "cleared", properties={str(numeric_definition.id): 15}
+ )
+ clear_result = api.set_external_account_custom_properties(
+ self.team.id, "cleared", properties={str(numeric_definition.id): None}
+ )
+ assert set_result.error is None
+ assert clear_result.error is None
+ assert (
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .filter(account_id=cleared_account.id, definition_id=numeric_definition.id, is_deleted=True, value_num=15)
+ .exists()
+ )
response = self._run(
AccountsTableQuery(
@@ -171,6 +185,10 @@ class TestAccountsTableQueryRunner(BaseTest):
}
assert [point.value for point in full_row.customPropertyHistory[str(numeric_definition.id)]] == [10.0, 20.0]
+ cleared_row = rows[str(cleared_account.id)]
+ assert cleared_row.customProperties == {str(numeric_definition.id): None, str(text_definition.id): None}
+ assert cleared_row.customPropertyHistory == {str(numeric_definition.id): []}
+
empty_row = rows[str(empty_account.id)]
assert empty_row.accountFields == {"stripe_customer_id": None, "churned_at": None, "ignored_at": None}
assert empty_row.tags == []
diff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.py
index bdfd0846b16d..d835e2a3474e 100644
--- a/products/customer_analytics/backend/logic/custom_property_values.py
+++ b/products/customer_analytics/backend/logic/custom_property_values.py
@@ -110,11 +110,11 @@ def set_account_custom_properties_by_id(
actor: User | None = None,
workflow_id: str | None = None,
) -> list[CustomPropertyValue]:
- """Set several of an account's custom property values, addressing each by definition id.
+ """Set or clear several account custom property values by definition id.
- Resolves each id to its team-scoped definition, then applies the same coerce + soft-delete +
- insert as `set_custom_property_value`. Caller is responsible for wrapping the batch in a
- transaction when all-or-nothing semantics are required.
+ Resolves each id to its team-scoped definition. A null value soft-deletes the active row.
+ Other values apply the same coerce + soft-delete + insert as `set_custom_property_value`.
+ Caller is responsible for wrapping the batch in a transaction when all-or-nothing semantics are required.
Raises `CustomPropertyDefinitionNotFound` (unknown id, carrying the id),
`InvalidCustomPropertyValue` (value doesn't match the data type, carrying the id in `field`),
@@ -127,6 +127,15 @@ def set_account_custom_properties_by_id(
definition = CustomPropertyDefinition.objects.for_team(team_id).get(id=definition_id)
except (CustomPropertyDefinition.DoesNotExist, ValidationError) as exc:
raise CustomPropertyDefinitionNotFound(definition_id) from exc
+ if value is None:
+ _clear_value(
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ actor=actor,
+ workflow_id=workflow_id,
+ )
+ continue
try:
row = _set_value(
team_id=team_id,
@@ -256,13 +265,44 @@ def _set_value(
return row
+def _clear_value(
+ *,
+ team_id: int,
+ account_id: str | UUID,
+ definition: CustomPropertyDefinition,
+ actor: User | None = None,
+ workflow_id: str | None = None,
+) -> None:
+ with transaction.atomic():
+ active_rows = CustomPropertyValue.objects.for_team(team_id).filter(
+ account_id=account_id, definition_id=definition.id, is_deleted=False
+ )
+ previous_row = active_rows.first()
+ if previous_row is None:
+ return
+ cleared_rows = active_rows.filter(id=previous_row.id).update(is_deleted=True)
+ if cleared_rows == 0:
+ raise CustomPropertyValueConflict(
+ f"An active value for custom property '{definition.name}' was changed concurrently."
+ )
+ _schedule_value_changed_event(
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ previous_row=previous_row,
+ current_value=None,
+ actor=actor,
+ workflow_id=workflow_id,
+ )
+
+
def _schedule_value_changed_event(
*,
team_id: int,
account_id: str | UUID,
definition: CustomPropertyDefinition,
previous_row: CustomPropertyValue | None,
- current_value: CoercedValue,
+ current_value: CoercedValue | None,
actor: User | None,
workflow_id: str | None,
) -> None:
diff --git a/products/customer_analytics/backend/presentation/views/account_actions.py b/products/customer_analytics/backend/presentation/views/account_actions.py
index 42e5e51726d5..eaa5e337767d 100644
--- a/products/customer_analytics/backend/presentation/views/account_actions.py
+++ b/products/customer_analytics/backend/presentation/views/account_actions.py
@@ -155,17 +155,17 @@ class ExternalAccountCreateSerializer(serializers.Serializer):
)
-@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}]})
+@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"}]})
class _CustomPropertyScalarField(serializers.Field):
- """A custom property value sent over the external API — a JSON scalar.
+ """A custom property value sent over the external API — a JSON scalar or null.
- Objects, arrays, and null are rejected here; the concrete type each property accepts is set by
- its definition and validated server-side when the value is coerced.
+ The concrete type each property accepts is set by its definition and validated server-side when
+ the value is coerced. Null clears the active value.
"""
def to_internal_value(self, data: Any) -> Any:
- if data is None or isinstance(data, dict | list):
- raise serializers.ValidationError("Value must be a string, number, or boolean.")
+ if isinstance(data, dict | list):
+ raise serializers.ValidationError("Value must be a string, number, boolean, or null.")
return data
@@ -175,8 +175,11 @@ class ExternalAccountCustomPropertiesSerializer(serializers.Serializer):
help_text="External ID of the account whose custom property values to set — the group key it is linked to.",
)
properties = serializers.DictField(
- child=_CustomPropertyScalarField(),
- help_text="Map of custom property definition UUID to the value to set for this account.",
+ child=_CustomPropertyScalarField(allow_null=True),
+ help_text=(
+ "Map of custom property definition UUID to the value to set for this account. Use null to clear an "
+ "active value. Omitted definitions are unchanged."
+ ),
)
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
index f35c7ee44f4e..b43bfe80deb3 100644
--- a/products/customer_analytics/backend/test/test_custom_property_values.py
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -273,6 +273,20 @@ class TestSetCustomPropertyValue(BaseTest):
with pytest.raises(IntegrityError):
self._set(definition=definition, value="enterprise")
+ @patch(f"{LOGIC_MODULE}.CustomPropertyValue")
+ def test_losing_the_active_value_clear_race_surfaces_as_a_conflict(self, mock_value_model):
+ definition = self._create_property_definition()
+ active_rows = mock_value_model.objects.for_team.return_value.filter.return_value
+ active_rows.first.return_value = MagicMock(id=uuid4())
+ active_rows.filter.return_value.update.return_value = 0
+
+ with pytest.raises(CustomPropertyValueConflict):
+ set_account_custom_properties_by_id(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ properties={str(definition.id): None},
+ )
+
class TestSetAccountCustomPropertiesById(BaseTest):
def setUp(self):
@@ -625,6 +639,33 @@ class TestSetExternalAccountCustomProperties(BaseTest):
assert result.values is not None
assert {(v.value) for v in result.values} == {"enterprise", 42.0}
+ def test_batch_clears_an_active_value_and_returns_only_set_values(self):
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=DisplayType.TEXT)
+ seats = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)
+ region = create_custom_property_definition(team_id=self.team.id, name="Region", display_type=DisplayType.TEXT)
+ facade.set_external_account_custom_properties(
+ self.team.id, "acme-1", properties={str(plan.id): "enterprise", str(region.id): "US"}
+ )
+
+ result = facade.set_external_account_custom_properties(
+ self.team.id, "acme-1", properties={str(plan.id): None, str(seats.id): 42}
+ )
+
+ assert result.error is None
+ assert result.values is not None
+ assert [(value.definition_id, value.value) for value in result.values] == [(seats.id, 42.0)]
+ assert (
+ not CustomPropertyValue.objects.for_team(self.team.id)
+ .filter(account=self.account, definition=plan, is_deleted=False)
+ .exists()
+ )
+ assert (
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .get(account=self.account, definition=region, is_deleted=False)
+ .value_str
+ == "US"
+ )
+
def test_unknown_external_id_returns_account_not_found(self):
plan = create_custom_property_definition(team_id=self.team.id, name="Plan")
result = facade.set_external_account_custom_properties(self.team.id, "missing", properties={str(plan.id): "x"})
diff --git a/products/customer_analytics/backend/test/test_events.py b/products/customer_analytics/backend/test/test_events.py
index aa42079f7126..5bbfbb9f5f27 100644
--- a/products/customer_analytics/backend/test/test_events.py
+++ b/products/customer_analytics/backend/test/test_events.py
@@ -310,6 +310,36 @@ class TestAccountCustomPropertyChangedEvent(BaseTest):
assert event["properties"]["actor_type"] == "workflow"
assert event["properties"]["workflow_id"] == WORKFLOW_ID
+ def test_workflow_clear_emits_null_current_value(self, mock_capture):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ self._set_value(definition, "silver")
+ mock_capture.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ result = facade.set_external_account_custom_properties(
+ self.team.id, "acme-1", properties={str(definition.id): None}, workflow_id=WORKFLOW_ID
+ )
+
+ assert result.error is None
+ assert result.values == []
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ assert event["properties"]["previous_value"] == "silver"
+ assert event["properties"]["current_value"] is None
+ assert event["properties"]["actor_type"] == "workflow"
+
+ def test_clearing_an_unset_value_emits_nothing(self, mock_capture):
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+
+ with self.captureOnCommitCallbacks(execute=True):
+ result = facade.set_external_account_custom_properties(
+ self.team.id, "acme-1", properties={str(definition.id): None}, workflow_id=WORKFLOW_ID
+ )
+
+ assert result.error is None
+ assert result.values == []
+ mock_capture.assert_not_called()
+
def test_user_actor_populates_actor_fields(self, mock_capture):
definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
self._set_value(definition, "silver")
diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.py
index 7170a6848612..a1adb39a7cb8 100644
--- a/products/customer_analytics/backend/test/test_external.py
+++ b/products/customer_analytics/backend/test/test_external.py
@@ -526,6 +526,20 @@ class TestExternalAccountCustomPropertiesAPI(APIBaseTest):
},
)
+ def test_null_clears_an_active_value_and_returns_no_values(self):
+ response = self._patch({"external_id": "acme-1", "properties": {str(self.plan.id): "enterprise"}})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ response = self._patch({"external_id": "acme-1", "properties": {str(self.plan.id): None}})
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["values"], [])
+ self.assertFalse(
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .filter(account=self.account, definition=self.plan, is_deleted=False)
+ .exists()
+ )
+
def test_unknown_external_id_returns_404(self):
response = self._patch({"external_id": "missing", "properties": {str(self.plan.id): "x"}})
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
diff --git a/products/customer_analytics/frontend/components/AccountPropertiesInput/CyclotronJobInputAccountProperties.test.tsx b/products/customer_analytics/frontend/components/AccountPropertiesInput/CyclotronJobInputAccountProperties.test.tsx
new file mode 100644
index 000000000000..bf1d7f284ffd
--- /dev/null
+++ b/products/customer_analytics/frontend/components/AccountPropertiesInput/CyclotronJobInputAccountProperties.test.tsx
@@ -0,0 +1,70 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render } from '@testing-library/react'
+import { useValues } from 'kea'
+import type { PropsWithChildren } from 'react'
+
+import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { accountPropertiesInputLogic } from './accountPropertiesInputLogic'
+import CyclotronJobInputAccountProperties from './CyclotronJobInputAccountProperties'
+
+jest.mock('kea', () => ({ ...jest.requireActual('kea'), useValues: jest.fn() }))
+jest.mock('lib/monaco/CodeEditorInline', () => ({
+ CodeEditorInline: (): JSX.Element => <div />,
+}))
+jest.mock('lib/ui/quill', () => ({
+ Combobox: ({ children }: PropsWithChildren): JSX.Element => <>{children}</>,
+ ComboboxContent: ({ children }: PropsWithChildren): JSX.Element => <div>{children}</div>,
+ ComboboxEmpty: ({ children }: PropsWithChildren): JSX.Element => <div>{children}</div>,
+ ComboboxInput: (): JSX.Element => <input />,
+ ComboboxItem: ({ children }: PropsWithChildren): JSX.Element => <div>{children}</div>,
+ ComboboxList: (): null => null,
+}))
+
+describe('CyclotronJobInputAccountProperties', () => {
+ const propertyDefinition: CustomPropertyDefinitionApi = {
+ id: 'property-id',
+ name: 'Text property',
+ display_type: 'text',
+ is_canonical: false,
+ has_workflow_reference: false,
+ source: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: 1,
+ updated_at: null,
+ references: [],
+ }
+
+ beforeEach(() => {
+ ;(useValues as jest.Mock).mockImplementation((logic) => {
+ if (logic === accountPropertiesInputLogic) {
+ return { definitions: [propertyDefinition], definitionsLoading: false }
+ }
+ throw new Error('Unexpected logic')
+ })
+ })
+
+ afterEach(cleanup)
+
+ it('marks a cleared property without removing its definition key', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ <CyclotronJobInputAccountProperties
+ schema={{
+ type: 'customer_analytics_account_properties',
+ key: 'account_properties',
+ label: 'Account properties',
+ }}
+ value={{ 'property-id': 'properties.plan' }}
+ onChange={onChange}
+ />
+ )
+
+ const clearButton = container.querySelector('[data-attr="account-properties-clear-property"]')
+ expect(clearButton).toBeInTheDocument()
+ fireEvent.click(clearButton as HTMLElement)
+
+ expect(onChange).toHaveBeenCalledWith({ 'property-id': { __posthog_clear_property: true } })
+ })
+})
diff --git a/products/customer_analytics/frontend/components/AccountPropertiesInput/CyclotronJobInputAccountProperties.tsx b/products/customer_analytics/frontend/components/AccountPropertiesInput/CyclotronJobInputAccountProperties.tsx
index 4758ae291250..f394a1c7b4a7 100644
--- a/products/customer_analytics/frontend/components/AccountPropertiesInput/CyclotronJobInputAccountProperties.tsx
+++ b/products/customer_analytics/frontend/components/AccountPropertiesInput/CyclotronJobInputAccountProperties.tsx
@@ -13,6 +13,15 @@ import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/fr
import { accountPropertiesInputLogic } from './accountPropertiesInputLogic'
+type ClearPropertyMarker = { __posthog_clear_property: true }
+type AccountProperties = Record<string, string | ClearPropertyMarker>
+
+function isClearPropertyMarker(value: unknown): value is ClearPropertyMarker {
+ return (
+ value !== null && typeof value === 'object' && (value as ClearPropertyMarker).__posthog_clear_property === true
+ )
+}
+
export default function CyclotronJobInputAccountProperties({
value,
onChange,
@@ -20,14 +29,16 @@ export default function CyclotronJobInputAccountProperties({
}: CustomInputRendererProps): JSX.Element {
const { definitions, definitionsLoading } = useValues(accountPropertiesInputLogic)
- // Keys are custom property definition ids (stable across renames); values are Hog expressions
- // (select properties store the chosen option label as a literal).
- const properties: Record<string, string> = value ?? {}
+ // Keys stay stable across property renames. The marker distinguishes a user-selected clear
+ // from a template that resolves to null.
+ // Select properties store the chosen option label as a literal.
+ const properties: AccountProperties = value ?? {}
const entries = Object.entries(properties)
const selectedIds = new Set(entries.map(([id]) => id))
const available = definitions.filter((d) => !selectedIds.has(d.id))
const setProperty = (id: string, hogValue: string): void => onChange({ ...properties, [id]: hogValue })
+ const clearProperty = (id: string): void => onChange({ ...properties, [id]: { __posthog_clear_property: true } })
const addProperty = (id: string): void => onChange({ ...properties, [id]: '' })
const removeProperty = (id: string): void => {
const next = { ...properties }
@@ -40,11 +51,20 @@ export default function CyclotronJobInputAccountProperties({
{entries.map(([id, hogValue]) => {
const definition = definitions.find((d) => d.id === id)
return (
- <div className="flex gap-2 items-center" key={id}>
+ <div className="flex flex-wrap gap-2 items-center" key={id}>
<div className="flex-1 min-w-50 font-medium truncate" title={definition?.name ?? id}>
{definition?.name ?? <span className="text-secondary italic">Unknown property</span>}
</div>
- {definition?.display_type === 'select' ? (
+ {isClearPropertyMarker(hogValue) ? (
+ <LemonButton
+ type="secondary"
+ size="small"
+ data-attr="account-properties-set-value"
+ onClick={() => setProperty(id, '')}
+ >
+ Set value
+ </LemonButton>
+ ) : definition?.display_type === 'select' ? (
<LemonSelect
className="flex-2"
value={hogValue || null}
@@ -70,6 +90,16 @@ export default function CyclotronJobInputAccountProperties({
globals={sampleGlobalsWithInputs ?? undefined}
/>
)}
+ {!isClearPropertyMarker(hogValue) && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ data-attr="account-properties-clear-property"
+ onClick={() => clearProperty(id)}
+ >
+ Clear property
+ </LemonButton>
+ )}
<LemonButton icon={<IconX />} size="small" onClick={() => removeProperty(id)} />
</div>
)
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts
index 75474b861715..76b1aa48b1ac 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts
@@ -155,7 +155,7 @@ registerActionNodeCategory({
{
type: 'function',
name: 'Update account property',
- description: 'Set custom property values on a Customer analytics account.',
+ description: 'Set or clear custom property values on a Customer analytics account.',
config: { template_id: 'template-posthog-update-account-property', inputs: {} },
getDefaultInputs: getAccountExternalIdDefaultInputs,
output_variable: { key: 'account', result_path: null },