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.

fix(ingestion): keep a group at the event filter tree root (#62445)

Paweł Ledwoń2a7483524e40
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 267ac2e64c67..2d953a91f497 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4746,6 +4746,10 @@ snapshots:
hash: v1.k794b7964.241ca6352364efc887eb32759aaa96ae0ff93d3cf21be7d8fbd5032bc7d58744.j-U61D5ssKdEhV9WCyEgR_571UQZK9m_iekEU1lzjOU
scenes-app-data-pipelines-event-filtering--single-condition--light:
hash: v1.k794b7964.654785f46f338c9d70eaca3ca79a94dab9fad11d53d181f8cceb47f5c63bc7fe.DbcJz_BltmCqPJ7Vt6ltmCkK93W0lSjHJC2yeBhOedE
+ scenes-app-data-pipelines-event-filtering--single-condition-root-is-editable--dark:
+ hash: v1.k794b7964.ec8d51d0f3575a14ff1d475fb7e80cee563a885b3e42c3e3013715e74b8c22f0.whV3GNR0rpMn7AQzwWDaLbgtDZ_0bCRcL_RDryWRdEU
+ scenes-app-data-pipelines-event-filtering--single-condition-root-is-editable--light:
+ hash: v1.k794b7964.ffc2f29fa56ddd5603428d5d0bf495be64ff40686fd6d73bcb5a9ac7d1f4e2fd.9NmyKM03GKv4v_V2pYq-CMXBWjFEE_YRfB5Es8FbMbM
scenes-app-data-pipelines-event-filtering--switch-mode-to-dry-run--dark:
hash: v1.k794b7964.6b80e9052b063c0763a074015093299d509932a53547c5e35ca654b76817fa02.Ky-1qxUDc4jUpY10x0Silq9QdkVjc0aAkRajQPW9oxM
scenes-app-data-pipelines-event-filtering--switch-mode-to-dry-run--light:
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx
index 44a7690c5c93..19ac0cc6ebac 100644
--- a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx
+++ b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx
@@ -271,6 +271,48 @@ Expected to show:
},
}
+export const SingleConditionRootIsEditable: Story = {
+ // Regression: mirrors a real production record. The backend used to prune a
+ // one-condition filter down to a bare `condition` root, which the editor
+ // rendered with no enclosing group — and therefore no "Add condition" /
+ // "Add group" buttons, stranding the user. The logic now re-wraps a
+ // non-group root in an OR on load so the add affordances are always present.
+ render: withFilter({
+ mode: 'live',
+ filter_tree: { type: 'condition', field: 'distinct_id', operator: 'contains', value: 'bot-' },
+ test_cases: [{ event_name: '', distinct_id: 'bot-crawler', expected_result: 'drop' }],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+A filter loaded from the API as a bare \`condition\` root (no enclosing group).
+
+Expected to show:
+- The single \`distinct_id ~ "bot-"\` condition row, now hosted inside a root OR group
+- "Add condition" and "Add group" buttons present (the root is normalized to a group on load)
+- One test case with a green "Pass" tag
+ `,
+ },
+ },
+ },
+ play: async () => {
+ // Wait for the loaded condition to render.
+ await waitFor(() => {
+ if (!document.querySelector('input[value="bot-"]')) {
+ throw new Error('Tree not loaded')
+ }
+ })
+ // The root must be wrapped into a group so the add affordance exists.
+ // Before the fix this button is absent and the story fails here.
+ await waitFor(() => {
+ if (!document.querySelector('[data-attr="add-condition-root"]')) {
+ throw new Error('Add condition button missing for single-condition root')
+ }
+ })
+ },
+}
+
export const EmptyGroupsInTree: Story = {
render: withFilter({
filter_tree: {
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.test.ts b/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.test.ts
index df06b1f90903..474f24592a49 100644
--- a/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.test.ts
+++ b/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.test.ts
@@ -2,6 +2,7 @@ import {
countConditions,
evaluateFilterTree,
FilterNode,
+ normalizeRootToGroup,
treeHasConditions,
treeHasEmptyValues,
updateAtPath,
@@ -272,6 +273,25 @@ describe('updateAtPath', () => {
})
})
+describe('normalizeRootToGroup', () => {
+ // Regression: the backend prunes single-child groups, so a saved one-condition
+ // filter loads back as a bare condition (or NOT) with no group to host the
+ // "Add condition"/"Add group" buttons. Re-wrap any non-group root in an OR.
+ it.each([
+ ['bare condition', cond('distinct_id', 'contains', 'bot')],
+ ['NOT node', not(cond())],
+ ])('wraps a %s root in an OR group', (_name, node) => {
+ expect(normalizeRootToGroup(node)).toEqual(or(node))
+ })
+
+ it.each([
+ ['OR', or(cond(), cond('distinct_id', 'exact', 'u1'))],
+ ['AND', and(cond())],
+ ])('leaves an %s root unchanged (same reference)', (_name, tree) => {
+ expect(normalizeRootToGroup(tree)).toBe(tree)
+ })
+})
+
describe('treeHasConditions', () => {
it.each([
['bare condition', cond(), true],
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.ts b/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.ts
index c7698d2da4ed..e17a542ec47d 100644
--- a/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.ts
+++ b/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.ts
@@ -198,6 +198,20 @@ export function treeHasEmptyValues(node: FilterNode): boolean {
}
}
+/**
+ * Ensure the root is an and/or group. The editor can only add conditions or
+ * groups inside a group node, and the backend prunes single-child groups — so a
+ * saved one-condition filter loads back as a bare condition (or NOT) with no
+ * group to host the "Add condition"/"Add group" buttons. Wrap any non-group root
+ * in an OR so the add affordances are always present.
+ */
+export function normalizeRootToGroup(node: FilterNode): FilterNode {
+ if (node.type === 'and' || node.type === 'or') {
+ return node
+ }
+ return { type: 'or', children: [node] }
+}
+
// --- Immutable tree updates ---
/**
@@ -421,7 +435,7 @@ export const eventFilterLogic = kea<eventFilterLogicType>([
actions.setFilterFormValue('id', data.id)
actions.setFilterFormValue('mode', data.mode ?? 'disabled')
if (data.filter_tree?.type) {
- actions.setFilterFormValue('filter_tree', data.filter_tree)
+ actions.setFilterFormValue('filter_tree', normalizeRootToGroup(data.filter_tree))
}
const testCases = (data.test_cases ?? []).map((tc: Omit<TestCase, '_key'>) => ({
...tc,
diff --git a/posthog/api/test/test_event_filter_config.py b/posthog/api/test/test_event_filter_config.py
index 6bf758d92a9f..ae1b0bf7c0ce 100644
--- a/posthog/api/test/test_event_filter_config.py
+++ b/posthog/api/test/test_event_filter_config.py
@@ -39,7 +39,7 @@ class TestEventFilterConfigAPI(APIBaseTest):
self.assertFalse(EventFilterConfig.objects.filter(team=self.team).exists())
def test_list_returns_existing_config(self):
- tree = _cond()
+ tree = _or(_cond())
EventFilterConfig.objects.create(team=self.team, mode=EventFilterMode.LIVE, filter_tree=tree)
response = self.client.get(self._url())
@@ -89,7 +89,7 @@ class TestEventFilterConfigAPI(APIBaseTest):
def test_create_upserts_filter_tree(self):
seed = self._seed_config()
- new_tree = _cond("distinct_id", "exact", "user-1")
+ new_tree = _or(_cond("distinct_id", "exact", "user-1"))
new_test_cases = [
{"distinct_id": "user-1", "expected_result": "drop"},
{"distinct_id": "someone-else", "expected_result": "ingest"},
@@ -149,11 +149,12 @@ class TestEventFilterConfigAPI(APIBaseTest):
self.assertEqual(EventFilterConfig.objects.filter(team=self.team).count(), 1)
def test_create_prunes_filter_tree_on_save(self):
- tree = _and(_cond())
+ # Empty/single-child nested groups are pruned, but the root stays a group.
+ tree = _or(_and(_cond()), {"type": "and", "children": []})
response = self.client.post(self._url(), data={"filter_tree": tree}, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["filter_tree"], _cond())
+ self.assertEqual(response.json()["filter_tree"], _or(_cond()))
def test_create_timestamps_are_read_only(self):
response = self.client.post(
diff --git a/posthog/models/event_filter_config.py b/posthog/models/event_filter_config.py
index 67c64aa4ed49..6de4410bd80d 100644
--- a/posthog/models/event_filter_config.py
+++ b/posthog/models/event_filter_config.py
@@ -82,21 +82,39 @@ class EventFilterConfig(UUIDTModel):
def prune_filter_tree(node: dict) -> dict | None:
- """Remove empty groups and collapse single-child groups."""
+ """
+ Remove empty groups and collapse single-child groups, keeping an and/or
+ group at the root.
+
+ The tree editor can only add conditions or groups inside a group node, so a
+ bare condition (or NOT) at the root leaves the user with no "Add condition"
+ button. We prune freely, then wrap a non-group root in an OR as a final pass.
+ """
+ pruned = _prune_node(node)
+ if pruned is not None and pruned.get("type") not in ("and", "or"):
+ return {"type": "or", "children": [pruned]}
+ return pruned
+
+
+def _prune_node(node: dict) -> dict | None:
+ """Remove empty groups and collapse single-child groups, depth-first."""
node_type = node.get("type")
if node_type == "condition":
return node
if node_type == "not":
- child = prune_filter_tree(node.get("child", {}))
+ child = _prune_node(node.get("child", {}))
if child is None:
return None
return {**node, "child": child}
if node_type in ("and", "or"):
- children = [prune_filter_tree(c) for c in node.get("children", [])]
- children = [c for c in children if c is not None]
+ children: list[dict] = []
+ for child in node.get("children", []):
+ pruned_child = _prune_node(child)
+ if pruned_child is not None:
+ children.append(pruned_child)
if len(children) == 0:
return None
if len(children) == 1:
diff --git a/posthog/models/test/test_event_filter_config.py b/posthog/models/test/test_event_filter_config.py
index dfed22754c6b..cc4b1a659647 100644
--- a/posthog/models/test/test_event_filter_config.py
+++ b/posthog/models/test/test_event_filter_config.py
@@ -156,8 +156,10 @@ class TestPruneFilterTree(SimpleTestCase):
self.assertIsNone(prune_filter_tree({"type": "and", "children": []}))
def test_collapses_single_child_group(self):
+ # Nested single-child groups collapse; the root stays a group (see
+ # TestPruneFilterTreePreservesGroupRoot).
cond = _cond()
- self.assertEqual(prune_filter_tree(_and(cond)), cond)
+ self.assertEqual(prune_filter_tree(_and(_or(cond), _cond(value="keep"))), _and(cond, _cond(value="keep")))
def test_removes_not_with_empty_child(self):
self.assertIsNone(prune_filter_tree(_not({"type": "or", "children": []})))
@@ -167,9 +169,40 @@ class TestPruneFilterTree(SimpleTestCase):
self.assertEqual(prune_filter_tree(tree), tree)
def test_collapses_nested_single_child_groups(self):
+ # Deeply nested single-child groups collapse down to one group at the root.
cond = _cond()
- tree = _or(_and(cond))
- self.assertEqual(prune_filter_tree(tree), cond)
+ self.assertEqual(prune_filter_tree(_or(_and(_or(cond)))), _or(cond))
+
+
+class TestPruneFilterTreePreservesGroupRoot(SimpleTestCase):
+ """
+ Regression: pruning must never leave a non-group (condition or NOT) at the
+ root. The tree editor can only add conditions/groups inside an and/or node,
+ so a bare-condition root strands the user with no "Add condition" button.
+ """
+
+ @parameterized.expand(
+ [
+ ("root_or_single_condition", _or(_cond()), [_cond()]),
+ ("root_and_single_condition", _and(_cond()), [_cond()]),
+ ("bare_condition_root", _cond("distinct_id", "contains", "bot"), [_cond("distinct_id", "contains", "bot")]),
+ ("bare_not_root", _not(_cond()), [_not(_cond())]),
+ ("nested_single_child_collapses", _or(_and(_cond())), [_cond()]),
+ ]
+ )
+ def test_root_is_a_group_wrapping_children(self, _name: str, tree: dict, expected_children: list[dict]):
+ pruned = prune_filter_tree(tree)
+ assert pruned is not None
+ self.assertIn(pruned["type"], ("and", "or"))
+ self.assertEqual(pruned["children"], expected_children)
+
+ def test_root_collapses_to_inner_group(self):
+ # The lone child is itself a group, so collapsing keeps a group root.
+ inner = _and(_cond(value="a"), _cond(value="b"))
+ self.assertEqual(prune_filter_tree(_or(inner)), inner)
+
+ def test_empty_root_group_still_returns_none(self):
+ self.assertIsNone(prune_filter_tree(_or()))
class TestEvaluateFilterTree(SimpleTestCase):
@@ -359,13 +392,38 @@ class TestEventFilterConfigModel(BaseTest):
self.assertIsNone(retrieved.filter_tree)
def test_save_prunes_filter_tree(self):
- tree = _and(_cond("event_name", "exact", "pageview"))
+ # Empty and single-child nested groups are pruned, but the root stays a group.
+ tree = _or(_and(_cond("event_name", "exact", "pageview")), {"type": "and", "children": []})
config = EventFilterConfig.objects.create(
team=self.team,
mode=EventFilterMode.LIVE,
filter_tree=tree,
)
- self.assertEqual(config.filter_tree, _cond("event_name", "exact", "pageview"))
+ self.assertEqual(config.filter_tree, _or(_cond("event_name", "exact", "pageview")))
+
+ def test_save_keeps_group_root_for_single_condition(self):
+ # Regression: a one-condition filter must round-trip as a group so the
+ # editor can still add conditions after reload.
+ config = EventFilterConfig.objects.create(
+ team=self.team,
+ mode=EventFilterMode.LIVE,
+ filter_tree=_or(_cond("distinct_id", "contains", "bot")),
+ )
+ assert config.filter_tree is not None
+ self.assertIn(config.filter_tree["type"], ("and", "or"))
+ self.assertEqual(config.filter_tree, _or(_cond("distinct_id", "contains", "bot")))
+
+ def test_save_wraps_bare_condition_root(self):
+ # Heals the production bug: a filter stored as a bare condition gets a
+ # group root the next time it is saved.
+ config = EventFilterConfig.objects.create(
+ team=self.team,
+ mode=EventFilterMode.LIVE,
+ filter_tree=_cond("distinct_id", "contains", "bot"),
+ )
+ assert config.filter_tree is not None
+ self.assertIn(config.filter_tree["type"], ("and", "or"))
+ self.assertEqual(config.filter_tree["children"], [_cond("distinct_id", "contains", "bot")])
def test_save_rejects_invalid_filter_tree(self):
with self.assertRaises(ValidationError):