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(ingestion): event ingestion filtering frontend (#53998)

Paweł Ledwoń9d314e05d026
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 06323f601fbf..97262cb0513c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -521,9 +521,9 @@ snapshots:
components-hogcharts-linechart--hovering-interior--light:
hash: v1.k794b7964.fbdce955d57f7fc414239a7dc502951925a647a510f59307b273a87a68acaa0a.tS4JZrw3ECahuMoFYTO3xoEJ89UQ84lFgvXFTKGwMNA
components-hogcharts-linechart--hovering-multi-series--dark:
- hash: v1.k794b7964.bc43065d43bc1e1238b514efd6bfbb3d1a2cc53f18c3cdcb59fdac8df9fe259b.zwrzaU3pqo3joC6IzW5dlDzp63ST6fjfuPyou6_72uc
+ hash: v1.k794b7964.da078843ba3e1569c6a36aa6f8ba3eb5f7dedc1852b4f256435711871b55a7ed.u12-UiyjvpbExGP33yhNmKIj7MefFMxWpXsGkf3VG74
components-hogcharts-linechart--hovering-multi-series--light:
- hash: v1.k794b7964.fbfe3904fa22e1871488ca2f9ddb30b569100259708a16b6fcb722a450857b1c.-4mxJ92opWKeOvWoHto-KHEH6pTxG56-q0ddN3nxW7Q
+ hash: v1.k794b7964.2fa5cdb17438c5d62f6b5c075c8160df3cc4c197754fe78c0bf722cd575b0dca.92ma-HCbFCtCf_jrLu2ntgzLy0g843soMAf-qaCna-E
components-hogcharts-linechart--hovering-over-aux-series--dark:
hash: v1.k794b7964.1381975ad1f3cd6f0bd026ed40e2cdbb4d2f373af40565d3e04b681767987402.4ZDmXP-Pet9NoUXCH9u5N9IYRT4kiX_tBklnhDqz7TU
components-hogcharts-linechart--hovering-over-aux-series--light:
@@ -1851,7 +1851,7 @@ snapshots:
filters-taxonomic-filter-headless--properties--dark:
hash: v1.k794b7964.4ee695e5751c6f73e9742ab0cfeecf61b5adfe829cf3a0d49ab2877cae8b212f.jPN9l5TDgLRy9NzHenXHCU903UDg8-GdeGpf4PXt7aA
filters-taxonomic-filter-headless--properties--light:
- hash: v1.k794b7964.bd715b36b456df8730e934366a35faed4556dffa881456db1272e2804047a036.IH74-bf3miZ6nC3E0bqbzIb0km4fBh97_2XubTpcmns
+ hash: v1.k794b7964.7af6b884e5d826df422db99e4a99d2172f3316561a499dbe386ea098b1fc54a9.rti2DMpqC0WEtd_AtG838vQlgQMHfwjBAR4uLN_HnUk
filters-taxonomic-filter-headless--suggested-filters-with-recents--dark:
hash: v1.k794b7964.c3a6cd419610bc486261efa753816547f080f00c838bde0b8720cf12067b3b22.nxBtExiDfJ3USkhV9RY1VPU_U2dGyEYCMFbhvtOcuVs
filters-taxonomic-filter-headless--suggested-filters-with-recents--light:
@@ -4302,6 +4302,82 @@ snapshots:
hash: v1.k794b7964.b7da818440cce605dcb07bb5f9148080c85cdad96b7546781450122607abd5a2.fnqTch61d1nE8VWTmjOT215WNlzEypscmrtWJ9uxgFo
scenes-app-data-management-revenue-analytics-event-configuration-modal--default--light:
hash: v1.k794b7964.92b5eaed847d1998fea36d7049c7b2b76f43864abd91784b77413bac1e28b453.cqyqE8dtKyCz3l0F9gcTHTOEt6s3Qzb1f-li3OIGkgY
+ scenes-app-data-pipelines-event-filtering--add-condition-and-test-case--dark:
+ hash: v1.k794b7964.1a2087b45be0688bc9085236aa51dbc7901591a4f29077eacef51727c5328f79.fT-9im3dQAt-gyHxFonAodgtx81iGmt22Usu3SmiSIM
+ scenes-app-data-pipelines-event-filtering--add-condition-and-test-case--light:
+ hash: v1.k794b7964.7c73afb6535de664eb894c3ebc4c7ea3de7994147a6b5fb950403ec9e9fef1a3.GE_TVJkvT0GixmS_ojCD8fZrT85Ox14-jRBGvqRsTXM
+ scenes-app-data-pipelines-event-filtering--at-max-conditions--dark:
+ hash: v1.k794b7964.6bfaad3a36dd5b63c14a92ddb20e9950d4f8df5bc85bac74128c402cd0fca6f5.m3hazhex8RQAZZ1Vg-9OpFgCWMo33UIMyPrC2teW7ec
+ scenes-app-data-pipelines-event-filtering--at-max-conditions--light:
+ hash: v1.k794b7964.ef6359d3fca8b95ed90e8c65d62c670526d635e9d6249974fdcb8ebc544e8c07.Fsc1wcVvL4-oM9pBe_UojkYkfoqP-tb6EbMthrFyiKg
+ scenes-app-data-pipelines-event-filtering--at-max-depth--dark:
+ hash: v1.k794b7964.3866f65b2294368626f0d24bba91119bba80f0c5e8489a4abadf302ae1f60878.6U9Qj5m4nQW11vK_62atdrlsCpxoLhsfGzIbWLkkDrw
+ scenes-app-data-pipelines-event-filtering--at-max-depth--light:
+ hash: v1.k794b7964.f82077b2c94152f956f3b35b5e556b95d493c990379a061f5ab68261ad8c1d82.YCyUjITNmHWW5YYzF_7yJEMrVIYTKxmURaKtCAtPE_E
+ scenes-app-data-pipelines-event-filtering--build-filter-from-scratch--dark:
+ hash: v1.k794b7964.f518b0107fbc1389fdfae383bdad885d1fae610e2e12b7e004d35c91025aee79.mBM3iBH6grdd-IdH2lSyOzsxWBX08OG_VfD0U32vXYg
+ scenes-app-data-pipelines-event-filtering--build-filter-from-scratch--light:
+ hash: v1.k794b7964.f105335dd0a0a1d35dfb8f64bdeaa899ab3fcc2e9270b756971e8e9994fed7f9.0CcuVu8fn4Q5znDCFtt9YU7jqC5G9TQIneWamQaTiGc
+ scenes-app-data-pipelines-event-filtering--deep-nested-tree--dark:
+ hash: v1.k794b7964.6fc0e1db4f51a831da4beb697a704c135542325b74de3dacdd84407ba0becc94.ywtC0KoCU_guvC94nGN_S3uvrPGHqnpCvaz7cJ0ylOI
+ scenes-app-data-pipelines-event-filtering--deep-nested-tree--light:
+ hash: v1.k794b7964.5bde36ae570efab7508c99591bd39dae56a7bbf3511760e4114ea066e5faca62.JWrN6DgRZUASJYK7k5zFKPjOTsxTYyzSBSGuuQE46hY
+ scenes-app-data-pipelines-event-filtering--disabled-with-conditions--dark:
+ hash: v1.k794b7964.cefe18e513c0460c19fb24dfcb2c3efec1e24267e102420ce6b376bdc2443f83._H4-9WxdvbLVFCXfWVqw8DLLYU49MHnn6VtZn1yTOr4
+ scenes-app-data-pipelines-event-filtering--disabled-with-conditions--light:
+ hash: v1.k794b7964.7e663a80676019399e7b0a22a96847cc420dfd42827d98b00361397c0650a218.FoBk0Or6h37obzoFVAJcMY6ozn_IT31-PJtgqwoO8EA
+ scenes-app-data-pipelines-event-filtering--dry-run-with-tests--dark:
+ hash: v1.k794b7964.56fb36dda6de613d01de4a4d9f66120645bcb7e06d2a8001d04836ada5db0cf6.T7Dy5FxPukbLK4gogusfXRAY8IEhoLSYTXNmy7niCvg
+ scenes-app-data-pipelines-event-filtering--dry-run-with-tests--light:
+ hash: v1.k794b7964.1ba198cdf9b38ec1d562b5663e6cfde2818b3daa101add24b22b0edfd34231ea.ssgY4QAMX_mjXCnIWdjMp-ZaiGmCUR7gWH2QxGuuk5g
+ scenes-app-data-pipelines-event-filtering--empty-groups-in-tree--dark:
+ hash: v1.k794b7964.dc170bd1bb08fe5afac0dc728068536326181e4ee075341bd667eb071ef0ff26.kPSFKe_Chg7ZMkvZtezEJSOCnBj4aYF3iBFODktMEro
+ scenes-app-data-pipelines-event-filtering--empty-groups-in-tree--light:
+ hash: v1.k794b7964.e745e1186140584f13920455034aafbcebefd31a75a72ada681c8d91519d17ca.RGFtdoBlGnkdGI2_k0mi7zMSEmDCxbckkoQfBqKbBew
+ scenes-app-data-pipelines-event-filtering--empty-state--dark:
+ hash: v1.k794b7964.2fe9a20989994989d0c2bb858b8810b26d6210905faec8a15315ac6e43c5f972.V5HdC2pqRdLr5RXBBUcjPvM02vHrutOSD9A4EWpjAYE
+ scenes-app-data-pipelines-event-filtering--empty-state--light:
+ hash: v1.k794b7964.3b862d74511c813ec7ea30085ab97cbc2c6064ac17f994018e9b2364d7c8fac3.1QBfYDtDuweXmu9RjzCHkn6xHlRG69AHZPzynOa5iFE
+ scenes-app-data-pipelines-event-filtering--failing-tests--dark:
+ hash: v1.k794b7964.e2e9d7f311bab64470a3f037c1a7d0d8e9be4a7fe8268cb829130cb85a8bb95d.O3B_Ge4Pt_zXsccGPRSraP-Di3dZs-u8Y28brK7z2-4
+ scenes-app-data-pipelines-event-filtering--failing-tests--light:
+ hash: v1.k794b7964.f03058a23f513c4a6ffc46286333a1d3ef80b5e20ce2f388a4ed9585266ea00c.Dpetxa4X85x2G4zep6LAL5gZkLByu6EZC1V5llWEhUg
+ scenes-app-data-pipelines-event-filtering--fix-failing-test-and-go-live--dark:
+ hash: v1.k794b7964.5c140a755d29473af67c853b0e19fed72720714a527cdad02958dc51b345a362.4uMVHXx6lEjtSOr1pIXMI0TsgKHQ3WCn2kGM99tnHOA
+ scenes-app-data-pipelines-event-filtering--fix-failing-test-and-go-live--light:
+ hash: v1.k794b7964.86ce14d7a09a0fdbb6f6786b57676d297b89da991942510e070fd53df20fda68.nMWIK_zP-04XWcGjcUjfJUhnVK7Sv_1RvNHlG6DQ42Q
+ scenes-app-data-pipelines-event-filtering--live-mode--dark:
+ hash: v1.k794b7964.d8a991c9f13b104591d49af4e1fb9cff74b19c7adff4d89973a0a16d13eb9640.2KgTbWN8uGPl4Ge0S3aqeSlGYi4xV9yIqhpXQPfYjqs
+ scenes-app-data-pipelines-event-filtering--live-mode--light:
+ hash: v1.k794b7964.3b67e943ab5f09a1ab90d710522e6389ed328bf0f7bb8d44e660b528903f8789.qRoUqSLsXr0z-C87p_jkG0jFy7z_3AWiZddCLt1cyIQ
+ scenes-app-data-pipelines-event-filtering--many-conditions--dark:
+ hash: v1.k794b7964.d1d50902f488484286d424a5a2068162005c7733defe4647a2275933d05fd881.86oz8Mi7Ne1129473NVicr-OqW5iWcKuBlkwEiVTCGQ
+ scenes-app-data-pipelines-event-filtering--many-conditions--light:
+ hash: v1.k794b7964.2cf08a3d69032568049faf0ad425b4de71b634a8fe99f742361d609fa0490dac.nkd2u1xpfTsBpkmmTpuIk3YC8cAsrdHtUpDQjYJqfx8
+ scenes-app-data-pipelines-event-filtering--many-test-cases--dark:
+ hash: v1.k794b7964.2b3f2079c09de617f4f611b61075c9b8aa2e89678d6e3e7d17d326337c7391e8.Cc1y1vM1UGaECxArQB4Tz80LB0MmlSekf7Y5f9BICm4
+ scenes-app-data-pipelines-event-filtering--many-test-cases--light:
+ hash: v1.k794b7964.3ea6cc29b30b68932510bad9af4fdaa3a1933b001f3cbaff625752e836d2f659.QmAglpVdDZPBbGnqtrrbEAtDD79ZgV3sjqm6BW2P7ZI
+ scenes-app-data-pipelines-event-filtering--not-wrapped-condition--dark:
+ hash: v1.k794b7964.c698ed3a3e3e39ccfb954d938e919855f4191105309184d81e5c35a32ccf3b50.N51HGP4PtYSn2FfuvbrysHBU53Ig9VQ2IhHBL77Zs9A
+ scenes-app-data-pipelines-event-filtering--not-wrapped-condition--light:
+ hash: v1.k794b7964.ba042b924af7703d05de81979fcf63dd1259f50b56d7052185001767b84bd064.XOuJiFG6fbZKg4dJ0eK_adqUkxaLCpuSzDqgOhNQnSw
+ scenes-app-data-pipelines-event-filtering--open-ascii-modal--dark:
+ hash: v1.k794b7964.eec05711cd83b10a9902049306f9d8eb3b4952150cc267868967206f27e950e7.LE2TKkr_7hoFoic6gr0tEq3206g2zzsXdOh2GtIx-dY
+ scenes-app-data-pipelines-event-filtering--open-ascii-modal--light:
+ hash: v1.k794b7964.7e6d72415df9f28d1a0fe4f8042111e88994638ad2c3b31ccd876610cd90db50.siXvMq3m0CXmWXkV9QdLga2BuqDFyQc52kUndZOOEDc
+ scenes-app-data-pipelines-event-filtering--remove-condition-and-add-group--dark:
+ hash: v1.k794b7964.4637d9a6264c31af3163597da07af13318c235792e6dbebe6d279008aab97a6a.Y97ffYWMq_VL5mJgAijjaCNnc0vCtOhKz8xe62B2mE0
+ scenes-app-data-pipelines-event-filtering--remove-condition-and-add-group--light:
+ hash: v1.k794b7964.5647250cd8bb31126dc5a03fea46a246b443217ad1b5f3b062cc13f2ae951447.DOtcxf0Mu_5nISyBrNZthiGE025rphxI3zNRw5KDrHY
+ scenes-app-data-pipelines-event-filtering--single-condition--dark:
+ 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--switch-mode-to-dry-run--dark:
+ hash: v1.k794b7964.6b80e9052b063c0763a074015093299d509932a53547c5e35ca654b76817fa02.Ky-1qxUDc4jUpY10x0Silq9QdkVjc0aAkRajQPW9oxM
+ scenes-app-data-pipelines-event-filtering--switch-mode-to-dry-run--light:
+ hash: v1.k794b7964.5e649d5ec0eb6f46fbfc1cf87bf07d8c9371d212abe8417a64ed52143ca1a16a.AjHxOZIVE8N3TxFNtbUVUvlSLSc0LgjR8oj9TbtBINg
scenes-app-data-warehouse-editor-upstream-graph--empty-state--dark:
hash: v1.k794b7964.0dc97f7b0c3ae81fcac98a415c7882c3a46bd371ce72a78ed05cb64f5e5f286a.l50zfPs-m7SlrgboOciMdUkiowPG7lbs8Bwft1UarRs
scenes-app-data-warehouse-editor-upstream-graph--empty-state--light:
@@ -4639,7 +4715,7 @@ snapshots:
scenes-app-insights-funnels--funnel-left-to-right-breakdown-edit--light:
hash: v1.k794b7964.414326f685dca45885b93d728ae8a75c7d8b600af35d76c9512a74a27e453006.IyZ8qHUwOv6qsBYvdUR1ZsK1Md_GNFCftDGvNZj78BQ
scenes-app-insights-funnels--funnel-left-to-right-edit--dark:
- hash: v1.k794b7964.c47bdb853ef9b6becfb675e2ca0bdbdb0c1b4385cf2442d50dd92752d90f7906.gaL7vRk-pWoOUkiPi-NGCd1W72x-M5l9jk5Qu-UcjwI
+ hash: v1.k794b7964.293297b83994468984576e5c15fa2cbbb2c4c0a7a8234959b9deba539efa383b.xupnP9sdcp25xPBOMzrhSHwtRpKPLKHaqLDBncapvQA
scenes-app-insights-funnels--funnel-left-to-right-edit--light:
hash: v1.k794b7964.c63132bb5b13cbe97938ebdb2e59e320ebc338bd12b2d3bfd6af81e56270650a.3gc3UBg-8GVo4HkNBH7UrogK2q1uh9pXPDjTdYGT8nc
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--medium--dark:
diff --git a/frontend/src/products.json b/frontend/src/products.json
index e931edb5617d..4b9095350477 100644
--- a/frontend/src/products.json
+++ b/frontend/src/products.json
@@ -252,6 +252,13 @@
"type": "hog_function/transformation",
"intents": []
},
+ {
+ "path": "Event ingestion filtering",
+ "category": "Pipeline",
+ "iconType": "data_pipeline_metadata",
+ "type": "event_filter",
+ "intents": []
+ },
{
"path": "Destinations",
"category": "Pipeline",
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index a65e8b6b9dc6..72718e2c7fa8 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -54,6 +54,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
NewAction: () => import('../../products/actions/frontend/pages/Action'),
BusinessKnowledge: () => import('../../products/business_knowledge/frontend/scenes/BusinessKnowledgeScene'),
Transformations: () => import('../../frontend/src/scenes/data-pipelines/TransformationsScene'),
+ EventFiltering: () => import('../../frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene'),
SupportTickets: () => import('../../products/conversations/frontend/scenes/tickets/SupportTicketsScene'),
SupportTicketDetail: () => import('../../products/conversations/frontend/scenes/ticket/SupportTicketScene'),
SupportSettings: () => import('../../products/conversations/frontend/scenes/settings/SupportSettingsScene'),
@@ -154,6 +155,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/data-management/actions/new/': ['NewAction', 'actionNew'],
'/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],
'/transformations': ['Transformations', 'transformations'],
+ '/event-filtering': ['EventFiltering', 'eventFiltering'],
'/support/tickets': ['SupportTickets', 'supportTickets'],
'/support/tickets/:ticketId': ['SupportTicketDetail', 'supportTicketDetail'],
'/support/settings': ['SupportSettings', 'supportSettings'],
@@ -442,6 +444,12 @@ export const productConfiguration: Record<string, any> = {
activityScope: 'HogFunction',
iconType: 'data_pipeline',
},
+ EventFiltering: {
+ projectBased: true,
+ name: 'Event ingestion filtering',
+ description: 'Drop events at ingestion time based on event metadata.',
+ iconType: 'data_pipeline',
+ },
SupportTickets: { name: 'Ticket list', projectBased: true, layout: 'app-container' },
SupportTicketDetail: { name: 'Ticket detail', projectBased: true, layout: 'app-container' },
SupportSettings: { name: 'Support settings', projectBased: true, layout: 'app-container' },
@@ -768,6 +776,7 @@ export const productUrls = {
actions: (): string => '/data-management/actions',
businessKnowledge: (): string => '/business-knowledge',
transformations: (): string => '/transformations',
+ eventFiltering: (): string => '/event-filtering',
cohort: (id: string | number): string => `/cohorts/${id}`,
cohorts: (): string => '/cohorts',
cohortCalculationHistory: (id: string | number): string => `/cohorts/${id}/calculation-history`,
@@ -2189,6 +2198,15 @@ export const getTreeItemsMetadata = (): FileSystemImport[] => [
sceneKey: 'EventDefinitions',
sceneKeys: ['EventDefinition', 'EventDefinitions'],
},
+ {
+ path: 'Event ingestion filtering',
+ category: 'Pipeline',
+ type: 'event_filter',
+ iconType: 'data_pipeline_metadata',
+ href: urls.eventFiltering(),
+ sceneKey: 'EventFiltering',
+ sceneKeys: ['EventFiltering'],
+ },
{
path: 'Event ingestion warnings',
category: 'Pipeline',
diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.ts
index 4a30458ec43b..b6e797f9ad4e 100644
--- a/frontend/src/scenes/appScenes.ts
+++ b/frontend/src/scenes/appScenes.ts
@@ -126,6 +126,7 @@ export const appScenes: Record<Scene | string, () => any> = {
[Scene.SystemStatus]: () => import('./instance/SystemStatus'),
[Scene.ToolbarLaunch]: () => import('./toolbar-launch/ToolbarLaunch'),
[Scene.Transformations]: () => import('./data-pipelines/TransformationsScene'),
+ [Scene.EventFiltering]: () => import('./data-pipelines/event-filtering/EventFilterScene'),
[Scene.Unsubscribe]: () => import('./Unsubscribe/Unsubscribe'),
[Scene.VercelConnect]: () => import('./authentication/VercelConnect'),
[Scene.VercelLinkError]: () => import('./authentication/VercelLinkError'),
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterMetrics.tsx b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterMetrics.tsx
new file mode 100644
index 000000000000..ce38e3fa7486
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterMetrics.tsx
@@ -0,0 +1,74 @@
+import { useValues } from 'kea'
+
+import { getColorVar } from 'lib/colors'
+import { AppMetricsFilters } from 'lib/components/AppMetrics/AppMetricsFilters'
+import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'
+import { AppMetricsTrends } from 'lib/components/AppMetrics/AppMetricsTrends'
+import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
+
+const EVENT_FILTER_METRIC_KEYS = ['dropped', 'would_be_dropped'] as const
+
+const EVENT_FILTER_METRICS_INFO: Record<string, { name: string; description: string; color: string }> = {
+ dropped: {
+ name: 'Dropped',
+ description: 'Approximate number of events dropped by the filter in live mode',
+ color: getColorVar('danger'),
+ },
+ would_be_dropped: {
+ name: 'Would be dropped',
+ description: 'Approximate number of events that matched the filter in dry run mode (not actually dropped)',
+ color: getColorVar('warning'),
+ },
+}
+
+export function EventFilterMetrics({ filterId }: { filterId: string | null }): JSX.Element | null {
+ const logicKey = `event-filter-metrics-${filterId ?? 'none'}`
+
+ const logic = filterId
+ ? appMetricsLogic({
+ logicKey,
+ loadOnMount: true,
+ loadOnChanges: true,
+ forceParams: {
+ appSource: 'event_filter',
+ appSourceId: filterId,
+ metricName: [...EVENT_FILTER_METRIC_KEYS],
+ breakdownBy: 'metric_name',
+ },
+ })
+ : null
+
+ const { appMetricsTrends, appMetricsTrendsLoading, getSingleTrendSeries } = useValues(
+ logic ?? appMetricsLogic({ logicKey: 'noop' })
+ )
+
+ if (!filterId) {
+ return null
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-row gap-2 flex-wrap justify-end">
+ <AppMetricsFilters logicKey={logicKey} />
+ </div>
+ <div className="flex flex-row gap-2 flex-wrap justify-center">
+ {EVENT_FILTER_METRIC_KEYS.map((key) => (
+ <AppMetricSummary
+ key={key}
+ name={EVENT_FILTER_METRICS_INFO[key].name}
+ description={EVENT_FILTER_METRICS_INFO[key].description}
+ loading={appMetricsTrendsLoading}
+ timeSeries={getSingleTrendSeries(key)}
+ previousPeriodTimeSeries={getSingleTrendSeries(key, true)}
+ color={EVENT_FILTER_METRICS_INFO[key].color}
+ colorIfZero={getColorVar('muted')}
+ />
+ ))}
+ </div>
+ <AppMetricsTrends appMetricsTrends={appMetricsTrends} loading={appMetricsTrendsLoading} />
+ <p className="text-muted text-xs">
+ These counts are approximate. The actual number of dropped events may differ by a small percentage.
+ </p>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx
new file mode 100644
index 000000000000..44a7690c5c93
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx
@@ -0,0 +1,906 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { waitFor } from '@testing-library/dom'
+import userEvent from '@testing-library/user-event'
+
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator, useStorybookMocks } from '~/mocks/browser'
+
+type Story = StoryObj<typeof App>
+
+const meta: Meta<typeof App> = {
+ title: 'Scenes-App/Data Pipelines/Event Filtering',
+ component: App,
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ pageUrl: urls.eventFiltering(),
+ // Pin "now" so the metrics chart's default `-7d` window — and any
+ // other date-derived UI — is stable across snapshot runs.
+ mockDate: '2026-05-25',
+ testOptions: {
+ waitForLoadersToDisappear: true,
+ },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/event_filter/': () => [204, null],
+ },
+ }),
+ ],
+}
+export default meta
+
+// --- Mock data ---
+
+const MOCK_ID = '019d6fed-835f-0000-a4e7-c2d7026252b4'
+
+const SIMPLE_FILTER = {
+ id: MOCK_ID,
+ mode: 'dry_run',
+ filter_tree: {
+ type: 'or',
+ children: [
+ { type: 'condition', field: 'event_name', operator: 'exact', value: '$drop_me' },
+ {
+ type: 'and',
+ children: [
+ { type: 'condition', field: 'event_name', operator: 'exact', value: '$internal' },
+ { type: 'condition', field: 'distinct_id', operator: 'contains', value: 'bot-' },
+ ],
+ },
+ ],
+ },
+ test_cases: [
+ { event_name: '$drop_me', distinct_id: 'user-1', expected_result: 'drop' },
+ { event_name: '$internal', distinct_id: 'bot-crawler', expected_result: 'drop' },
+ { event_name: '$internal', distinct_id: 'real-user', expected_result: 'ingest' },
+ { event_name: '$pageview', distinct_id: 'user-1', expected_result: 'ingest' },
+ ],
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+}
+
+// `EventFilterMetrics` doesn't hit `/event_filter/metrics/`; it goes through
+// `appMetricsLogic`, which posts HogQL queries to `/query/HogQLQuery/`. The
+// time-series query returns rows shaped `[dates, breakdown, totals]` and the
+// totals query returns rows shaped `[total, ...breakdowns]`. Both are fired
+// on mount, plus a separate previous-period time-series call.
+//
+// In live mode only `dropped` accumulates; in dry-run mode only
+// `would_be_dropped` accumulates (events match the filter but are not
+// actually dropped). The mocks below mirror that based on the form mode.
+
+const METRIC_DATES = [
+ '2026-05-18T00:00:00Z',
+ '2026-05-19T00:00:00Z',
+ '2026-05-20T00:00:00Z',
+ '2026-05-21T00:00:00Z',
+ '2026-05-22T00:00:00Z',
+ '2026-05-23T00:00:00Z',
+ '2026-05-24T00:00:00Z',
+]
+const METRIC_VALUES = [120, 95, 140, 110, 130, 105, 150]
+const METRIC_ZEROS = [0, 0, 0, 0, 0, 0, 0]
+const METRIC_TOTAL = METRIC_VALUES.reduce((sum, v) => sum + v, 0)
+
+const EMPTY_TIMESERIES_RESULTS: unknown[][] = []
+const EMPTY_TOTALS_RESULTS: unknown[][] = []
+
+function metricsHandler(
+ timeSeriesResults: unknown[][],
+ totalsResults: unknown[][]
+): (req: { json: () => Promise<unknown> }) => Promise<[number, unknown]> {
+ return async (req) => {
+ const body = (await req.json()) as { query?: { query?: string } }
+ const isTimeSeries = body.query?.query?.includes('calendar') ?? false
+ return [200, { results: isTimeSeries ? timeSeriesResults : totalsResults }]
+ }
+}
+
+function metricsForMode(mode: 'live' | 'dry_run'): {
+ timeSeries: unknown[][]
+ totals: unknown[][]
+} {
+ const isLive = mode === 'live'
+ return {
+ timeSeries: [
+ [METRIC_DATES, 'dropped', isLive ? METRIC_VALUES : METRIC_ZEROS],
+ [METRIC_DATES, 'would_be_dropped', isLive ? METRIC_ZEROS : METRIC_VALUES],
+ ],
+ totals: [
+ [isLive ? METRIC_TOTAL : 0, 'dropped'],
+ [isLive ? 0 : METRIC_TOTAL, 'would_be_dropped'],
+ ],
+ }
+}
+
+function withFilter(overrides: Record<string, unknown> = {}): () => JSX.Element {
+ return () => {
+ useStorybookMocks({
+ get: {
+ '/api/environments/:team_id/event_filter/': { ...SIMPLE_FILTER, ...overrides },
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind/': metricsHandler(
+ EMPTY_TIMESERIES_RESULTS,
+ EMPTY_TOTALS_RESULTS
+ ),
+ },
+ })
+ return <App />
+ }
+}
+
+function withFilterAndMetrics(overrides: Record<string, unknown> = {}): () => JSX.Element {
+ return () => {
+ const mode = (overrides.mode as 'live' | 'dry_run' | undefined) ?? (SIMPLE_FILTER.mode as 'dry_run')
+ const { timeSeries, totals } = metricsForMode(mode)
+ useStorybookMocks({
+ get: {
+ '/api/environments/:team_id/event_filter/': { ...SIMPLE_FILTER, ...overrides },
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind/': metricsHandler(timeSeries, totals),
+ },
+ })
+ return <App />
+ }
+}
+
+// ============================================================
+// Simple — basic visual states
+// ============================================================
+
+export const EmptyState: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Initial empty state shown when no filter config exists yet (API returns 204).
+
+Expected to show:
+- Status card labelled "Filter is disabled" with no colored border
+- Mode segmented button defaulting to "Disabled"
+- Empty filter tree with only an "Add condition" button
+- No test cases section content
+- No metrics chart
+ `,
+ },
+ },
+ },
+}
+
+export const DryRunWithTests: Story = {
+ render: withFilterAndMetrics(),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Dry-run mode with a populated filter, four test cases, and a sample metrics series.
+
+Expected to show:
+- Status card with yellow border, label "Filter is in dry run"
+- "Dry run" selected in the mode segmented button
+- Filter tree: root OR containing \`event_name = "$drop_me"\` and a nested AND group with two conditions
+- Four test cases, all with green "Pass" tags
+- Metrics summary: "Dropped" card shows 0 (+0.0%), "Would be dropped" card shows 850
+ (sum of the mocked values) — dry-run only counts matches, doesn't drop them
+- The Chart.js line graph canvas underneath is intentionally blank in snapshots
+ (Chart.ts overrides \`draw\` to skip rendering under the storybook test runner)
+ `,
+ },
+ },
+ },
+}
+
+export const LiveMode: Story = {
+ render: withFilterAndMetrics({ mode: 'live' }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Same filter as DryRunWithTests, switched to live mode.
+
+Expected to show:
+- Status card with green border, label "Filter is active"
+- "Live" selected in the mode segmented button
+- Status copy "Matching events are being dropped from ingestion."
+- Same tree and test cases as the dry-run story
+- Metrics summary: "Dropped" card shows 850 (sum of the mocked values),
+ "Would be dropped" card shows 0 — live mode actually drops, doesn't shadow-count
+- The Chart.js line graph canvas underneath is intentionally blank in snapshots
+ (Chart.ts overrides \`draw\` to skip rendering under the storybook test runner)
+ `,
+ },
+ },
+ },
+}
+
+export const DisabledWithConditions: Story = {
+ render: withFilter({ mode: 'disabled' }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Disabled mode with a configured filter tree and test cases — captures that nothing is dropped or counted
+even when the filter is fully set up.
+
+Expected to show:
+- Status card with no colored border, label "Filter is disabled"
+- "Disabled" selected in the mode segmented button
+- Status copy "No events are being filtered or counted."
+- Filter tree and test cases still rendered (same as DryRunWithTests)
+- Metrics chart renders empty (no series) — disabled mode produces no metrics
+ `,
+ },
+ },
+ },
+}
+
+// ============================================================
+// Edge cases
+// ============================================================
+
+export const SingleCondition: Story = {
+ render: withFilter({
+ filter_tree: {
+ type: 'or',
+ children: [{ type: 'condition', field: 'event_name', operator: 'exact', value: '$drop_me' }],
+ },
+ test_cases: [
+ { event_name: '$drop_me', distinct_id: 'user-1', expected_result: 'drop' },
+ { event_name: '$pageview', distinct_id: 'user-1', expected_result: 'ingest' },
+ ],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Smallest non-empty filter — root OR with a single condition. Used to confirm the tree renders
+correctly when there is no nested group to draw.
+
+Expected to show:
+- Root OR with exactly one condition row: \`event_name = "$drop_me"\`
+- Two test cases, both with green "Pass" tags
+ `,
+ },
+ },
+ },
+}
+
+export const EmptyGroupsInTree: Story = {
+ render: withFilter({
+ filter_tree: {
+ type: 'or',
+ children: [
+ { type: 'and', children: [] },
+ { type: 'condition', field: 'event_name', operator: 'exact', value: '$drop_me' },
+ ],
+ },
+ test_cases: [
+ { event_name: '$drop_me', distinct_id: 'user-1', expected_result: 'drop' },
+ { event_name: '$pageview', distinct_id: 'user-1', expected_result: 'ingest' },
+ ],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Root OR with an empty AND group alongside a real condition. Verifies that an empty group renders
+without crashing and that \`isTreeEmpty\` does not collapse the whole tree to "no conditions".
+
+Expected to show:
+- Root OR with two rows: an empty AND group (rendered with "Add condition" / "Add group" buttons,
+ no leaf rows) and \`event_name = "$drop_me"\`
+- Two test cases, both with green "Pass" tags
+ `,
+ },
+ },
+ },
+}
+
+export const NotWrappedCondition: Story = {
+ render: withFilter({
+ filter_tree: {
+ type: 'or',
+ children: [
+ {
+ type: 'not',
+ child: { type: 'condition', field: 'distinct_id', operator: 'contains', value: 'admin' },
+ },
+ ],
+ },
+ test_cases: [
+ { event_name: '$pageview', distinct_id: 'admin-user', expected_result: 'ingest' },
+ { event_name: '$pageview', distinct_id: 'regular-user', expected_result: 'drop' },
+ ],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Root OR containing a single NOT-wrapped condition. Covers the NOT wrapper rendering and its
+inverse evaluation semantics in the test-case Pass/Fail display.
+
+Expected to show:
+- Root OR with one row: a NOT wrapper around \`distinct_id ~ "admin"\`
+- Two test cases, both with green "Pass" tags (the admin user is "ingest", the regular user is "drop")
+ `,
+ },
+ },
+ },
+}
+
+export const FailingTests: Story = {
+ render: withFilter({
+ test_cases: [
+ ...SIMPLE_FILTER.test_cases,
+ { event_name: '$pageview', distinct_id: 'user-1', expected_result: 'drop' },
+ ],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Same SIMPLE_FILTER as DryRunWithTests with one extra test case whose expected outcome doesn't
+match the tree. Captures the failing-test UI plus the "tests failing — will be saved as dry run"
+hint surface.
+
+Expected to show:
+- Mode is "Dry run"; status card still yellow
+- Filter tree identical to DryRunWithTests
+- Five test cases: four with green "Pass" tags, one with a red "Fail" tag (the trailing
+ \`$pageview / user-1\` case)
+- Inline danger text "Tests failing — will be saved as dry run" only appears once the user
+ attempts to switch to live (not visible here)
+ `,
+ },
+ },
+ },
+}
+
+export const DeepNestedTree: Story = {
+ render: withFilter({
+ filter_tree: {
+ type: 'or',
+ children: [
+ { type: 'condition', field: 'event_name', operator: 'exact', value: '$drop_me' },
+ {
+ type: 'and',
+ children: [
+ {
+ type: 'or',
+ children: [
+ { type: 'condition', field: 'event_name', operator: 'exact', value: '$internal' },
+ { type: 'condition', field: 'event_name', operator: 'contains', value: 'bot_' },
+ ],
+ },
+ {
+ type: 'not',
+ child: { type: 'condition', field: 'distinct_id', operator: 'exact', value: 'admin-user' },
+ },
+ ],
+ },
+ ],
+ },
+ test_cases: [
+ { event_name: '$drop_me', distinct_id: 'anyone', expected_result: 'drop' },
+ { event_name: '$internal', distinct_id: 'user-1', expected_result: 'drop' },
+ { event_name: '$internal', distinct_id: 'admin-user', expected_result: 'ingest' },
+ { event_name: '$pageview', distinct_id: 'user-1', expected_result: 'ingest' },
+ ],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Tree exercising every node type at non-trivial depth: OR → (condition, AND → (OR → (condition, condition), NOT → condition)).
+
+Expected to show:
+- Root OR with two children: \`event_name = "$drop_me"\` and an AND group
+- The AND group contains a nested OR (two conditions) and a NOT-wrapped condition
+- Four test cases, all with green "Pass" tags
+ `,
+ },
+ },
+ },
+}
+
+export const ManyConditions: Story = {
+ render: withFilter({
+ filter_tree: {
+ type: 'or',
+ children: Array.from({ length: 10 }, (_, i) => ({
+ type: 'condition' as const,
+ field: 'event_name' as const,
+ operator: 'exact' as const,
+ value: `$event_${i}`,
+ })),
+ },
+ test_cases: [],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Root OR with 10 sibling conditions — stresses vertical layout and the "Add condition" button
+position when there are many siblings (but still under the max).
+
+Expected to show:
+- Root OR with 10 condition rows: \`event_name = "$event_0"\` … \`$event_9\`
+- "Add condition" and "Add group" buttons still enabled
+- Test cases section empty
+ `,
+ },
+ },
+ },
+}
+
+export const AtMaxConditions: Story = {
+ render: withFilter({
+ filter_tree: {
+ type: 'or',
+ children: Array.from({ length: 20 }, (_, i) => ({
+ type: 'condition' as const,
+ field: i % 2 === 0 ? ('event_name' as const) : ('distinct_id' as const),
+ operator: 'exact' as const,
+ value: `$event_${i}`,
+ })),
+ },
+ test_cases: [
+ { event_name: '$event_0', distinct_id: 'user-1', expected_result: 'drop' },
+ { event_name: '$nomatch', distinct_id: 'user-1', expected_result: 'ingest' },
+ ],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Filter at the EVENT_FILTER_MAX_CONDITIONS limit (20). Confirms that "Add condition" / "Add group"
+are disabled and the limit hint surfaces.
+
+Expected to show:
+- Root OR with 20 condition rows alternating between \`event_name\` and \`distinct_id\` fields
+- "Add condition" and "Add group" buttons rendered in their disabled state
+ (hovering them surfaces "Maximum of 20 conditions reached")
+- Two test cases, both with green "Pass" tags
+ `,
+ },
+ },
+ },
+}
+
+export const AtMaxDepth: Story = {
+ render: withFilter({
+ filter_tree: {
+ type: 'or',
+ children: [
+ {
+ // depth 1
+ type: 'and',
+ children: [
+ {
+ // depth 2
+ type: 'not',
+ child: {
+ // depth 3
+ type: 'and',
+ children: [
+ {
+ // depth 4 — deepest group; "Add group" disabled here
+ type: 'and',
+ children: [
+ {
+ // depth 5 — the limit
+ type: 'condition',
+ field: 'event_name',
+ operator: 'exact',
+ value: '$deepest',
+ },
+ ],
+ },
+ ],
+ },
+ },
+ { type: 'condition', field: 'event_name', operator: 'exact', value: '$shallow' },
+ ],
+ },
+ ],
+ },
+ test_cases: [
+ { event_name: '$shallow', distinct_id: 'user-1', expected_result: 'drop' },
+ { event_name: '$deepest', distinct_id: 'user-1', expected_result: 'ingest' },
+ ],
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Filter at the EVENT_FILTER_MAX_DEPTH limit (5 nesting levels). Confirms indentation, connector
+lines, and the "Add group" button being rendered in its disabled state inside the deepest group.
+The NOT sits at depth 2 so the deep chain still bottoms out in a group (AND at depth 4) rather
+than a NOT — which is what makes the depth-limit button state observable.
+
+Expected to show:
+- Visible nesting OR → AND → NOT → AND → AND → condition (\`$deepest\`)
+- Sibling \`event_name = "$shallow"\` rendered alongside the NOT at AND-depth-1
+- "Add group" rendered disabled inside the depth-4 AND group (its tooltip is
+ "Maximum nesting depth of 5 reached"); "Add condition" still enabled there
+- Two test cases, both with green "Pass" tags: \`$shallow\` drops (matches the shallow
+ sibling AND the NOT inverts the inner chain to true), \`$deepest\` ingests (NOT inverts
+ to false, so the AND short-circuits)
+ `,
+ },
+ },
+ },
+}
+
+export const ManyTestCases: Story = {
+ render: withFilter({
+ test_cases: Array.from({ length: 20 }, (_, i) => ({
+ event_name: i % 2 === 0 ? '$drop_me' : '$pageview',
+ distinct_id: `user-${i}`,
+ expected_result: i % 2 === 0 ? ('drop' as const) : ('ingest' as const),
+ })),
+ }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Same SIMPLE_FILTER tree with 20 test cases — stresses the test cases list layout and scrolling.
+
+Expected to show:
+- Filter tree identical to DryRunWithTests
+- 20 test case rows, alternating \`$drop_me\` and \`$pageview\`, all with green "Pass" tags
+ `,
+ },
+ },
+ },
+}
+
+// ============================================================
+// Interactive — play functions that simulate user actions
+// ============================================================
+
+export const AddConditionAndTestCase: Story = {
+ render: withFilter(),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Adds a condition to the root OR group and a new test case via the UI.
+
+Expected to show:
+- 4 value inputs in the tree (3 original + 1 new containing "$new_event")
+- 5 test cases (4 original + 1 new)
+- New test case's event name is "$new_event"
+- New test case shows a green "Pass" tag (matches the OR condition)
+ `,
+ },
+ },
+ },
+ play: async () => {
+ // Wait for the API mock to load the tree — `add-condition-root` is present
+ // immediately on mount with an empty default tree, so we must wait for the
+ // loaded conditions or `afterMount` will overwrite our edits mid-play.
+ await waitFor(() => {
+ if (!document.querySelector('input[value="$drop_me"]')) {
+ throw new Error('Tree not loaded')
+ }
+ })
+
+ const inputsBefore = document.querySelectorAll('input[placeholder="Value..."]').length
+
+ // Add a condition to the root OR
+ document.querySelector<HTMLElement>('[data-attr="add-condition-root"]')!.click()
+
+ // Wait for new input to appear
+ await waitFor(() => {
+ if (document.querySelectorAll('input[placeholder="Value..."]').length <= inputsBefore) {
+ throw new Error('New input not added')
+ }
+ })
+
+ // Fill the new condition (last Value... input)
+ const condInputs = document.querySelectorAll<HTMLInputElement>('input[placeholder="Value..."]')
+ const newCondInput = condInputs[condInputs.length - 1]
+ await userEvent.clear(newCondInput)
+ await userEvent.paste('$new_event')
+
+ const testCasesBefore = document.querySelectorAll('input[placeholder="$pageview"]').length
+
+ // Add a test case
+ Array.from(document.querySelectorAll('button'))
+ .find((b) => b.textContent?.trim() === 'Add test case')!
+ .click()
+
+ // Wait for test case input to appear
+ await waitFor(() => {
+ if (document.querySelectorAll('input[placeholder="$pageview"]').length <= testCasesBefore) {
+ throw new Error('Test case input not added')
+ }
+ })
+
+ // Fill test case event name (last $pageview input)
+ const eventInputs = document.querySelectorAll<HTMLInputElement>('input[placeholder="$pageview"]')
+ const newEventInput = eventInputs[eventInputs.length - 1]
+ await userEvent.clear(newEventInput)
+ await userEvent.paste('$new_event')
+ },
+}
+
+export const SwitchModeToDryRun: Story = {
+ render: withFilter({ mode: 'disabled' }),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Starts in disabled mode, then clicks the "Dry run" button.
+
+Expected to show:
+- Status card says "Filter is in dry run"
+- Status card has the warning (yellow) border
+- "Dry run" is selected in the segmented button
+ `,
+ },
+ },
+ },
+ play: async () => {
+ // Wait for the API mock to load the tree — otherwise `afterMount` can resolve
+ // after our click and overwrite the mode back to "disabled".
+ await waitFor(() => {
+ if (!document.querySelector('input[value="$drop_me"]')) {
+ throw new Error('Tree not loaded')
+ }
+ })
+
+ Array.from(document.querySelectorAll('button'))
+ .find((b) => b.textContent?.trim() === 'Dry run')!
+ .click()
+ },
+}
+
+export const FixFailingTestAndGoLive: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Starts with a failing test case ("$dro" expected to drop, but the filter is \`contains "drop"\`),
+fixes it by appending "p" to make "$drop", then clicks Live.
+
+Expected to show:
+- Status card says "Filter is active" with green border
+- "Live" is selected in the segmented button
+- Both test cases show green "Pass" tags (no red Fail tags)
+- Second test case event name is "$drop" (was "$dro", "p" appended)
+ `,
+ },
+ },
+ },
+ render: () => {
+ useStorybookMocks({
+ get: {
+ '/api/environments/:team_id/event_filter/': {
+ ...SIMPLE_FILTER,
+ filter_tree: {
+ type: 'or',
+ children: [{ type: 'condition', field: 'event_name', operator: 'contains', value: 'drop' }],
+ },
+ test_cases: [
+ { event_name: '$drop_me', distinct_id: 'user-1', expected_result: 'drop' },
+ { event_name: '$dro', distinct_id: 'user-1', expected_result: 'drop' },
+ ],
+ },
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind/': metricsHandler(
+ EMPTY_TIMESERIES_RESULTS,
+ EMPTY_TOTALS_RESULTS
+ ),
+ },
+ })
+ return <App />
+ },
+ play: async () => {
+ // Wait for the failing test
+ await waitFor(
+ () => {
+ if (!document.querySelector('.LemonTag--danger')) {
+ throw new Error('Fail tag not rendered')
+ }
+ },
+ { timeout: 5000 }
+ )
+
+ // Fix: append "p" to "$dro" → "$drop"
+ const failingInput = document.querySelector<HTMLInputElement>('input[value="$dro"]')!
+ await userEvent.type(failingInput, 'p')
+
+ // Wait for all tests to pass
+ await waitFor(() => {
+ if (document.querySelector('.LemonTag--danger')) {
+ throw new Error('Still has failing tests')
+ }
+ })
+
+ // Click Live
+ const allButtons = Array.from(document.querySelectorAll('button'))
+ const liveButton = allButtons.find((b) => b.textContent?.trim() === 'Live')!
+ await userEvent.click(liveButton)
+ },
+}
+
+export const OpenAsciiModal: Story = {
+ render: withFilter(),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Clicks "Show as ASCII" to open the expression preview modal.
+
+Expected to show:
+- Modal is open with title "Filter tree"
+- Modal shows the tree with "├──" and "└──" connectors
+- Tree contains "$drop_me", "$internal", "bot-"
+- OR at the root, AND as the nested group
+ `,
+ },
+ },
+ },
+ play: async () => {
+ // Wait for the API mock to load the tree before opening the modal — otherwise
+ // the snapshot can capture the modal rendered over the still-empty default tree.
+ await waitFor(() => {
+ if (!document.querySelector('input[value="$drop_me"]')) {
+ throw new Error('Tree not loaded')
+ }
+ })
+
+ Array.from(document.querySelectorAll('button'))
+ .find((b) => b.textContent?.trim() === 'Show as ASCII')!
+ .click()
+
+ await waitFor(() => {
+ const modal = document.querySelector('.LemonModal pre')
+ if (!modal?.textContent?.includes('├──')) {
+ throw new Error('ASCII modal not rendered')
+ }
+ })
+ },
+}
+
+export const RemoveConditionAndAddGroup: Story = {
+ render: withFilter(),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Removes the \`$drop_me\` condition, adds a new empty AND group at the root, then opens the
+ASCII modal to verify the resulting structure.
+
+Expected to show:
+- \`$drop_me\` condition is gone from the tree
+- Tree has 2 children in root OR: the original AND group + the new empty AND group
+- ASCII modal is open showing the tree structure
+- ASCII output contains "$internal", "bot-", and two AND groups
+ `,
+ },
+ },
+ },
+ play: async () => {
+ await waitFor(() => {
+ if (!document.querySelector('[data-attr="remove-0"]')) {
+ throw new Error('Tree not rendered')
+ }
+ })
+
+ // Remove $drop_me (path [0] in root OR)
+ document.querySelector<HTMLElement>('[data-attr="remove-0"]')!.click()
+
+ // Wait for removal — root OR should have only 1 child (no remove-1 button)
+ await waitFor(() => {
+ if (document.querySelector('[data-attr="remove-1"]')) {
+ throw new Error('Tree still has 2+ children in root OR')
+ }
+ })
+
+ // Add a group to the root OR
+ document.querySelector<HTMLElement>('[data-attr="add-group-root"]')!.click()
+
+ // Wait for new group to appear — root OR should have 2 children again
+ await waitFor(() => {
+ if (!document.querySelector('[data-attr="remove-1"]')) {
+ throw new Error('New group not added')
+ }
+ })
+
+ // Open ASCII modal to verify the tree structure
+ const allButtons = Array.from(document.querySelectorAll('button'))
+ const asciiButton = allButtons.find((b) => b.textContent?.trim() === 'Show as ASCII')!
+ asciiButton.click()
+
+ await waitFor(() => {
+ const modal = document.querySelector('.LemonModal pre')
+ if (!modal?.textContent?.includes('$internal')) {
+ throw new Error('ASCII modal not rendered')
+ }
+ })
+ },
+}
+
+export const BuildFilterFromScratch: Story = {
+ render: () => {
+ // 204 makes afterMount short-circuit, so the form keeps its defaults
+ // (empty OR, no test cases, disabled mode) and the play function can
+ // build the tree without racing the API load.
+ useStorybookMocks({
+ get: {
+ '/api/environments/:team_id/event_filter/': () => [204, null],
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind/': metricsHandler(
+ EMPTY_TIMESERIES_RESULTS,
+ EMPTY_TOTALS_RESULTS
+ ),
+ },
+ })
+ return <App />
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Starts from an empty filter and uses the UI to add one condition and one test case.
+
+Expected to show:
+- Tree has 1 condition: \`event_name = "$autocapture"\`
+- 1 test case with event name "$autocapture"
+- Test case shows a green "Pass" tag (default expected is "drop", matches the condition)
+- Mode is still "Disabled"
+ `,
+ },
+ },
+ },
+ play: async () => {
+ await waitFor(() => {
+ if (!document.querySelector('[data-attr="add-condition-root"]')) {
+ throw new Error('Empty tree not rendered')
+ }
+ })
+
+ // Add first condition
+ document.querySelector<HTMLElement>('[data-attr="add-condition-root"]')!.click()
+
+ // Wait for input to appear
+ await waitFor(() => {
+ if (!document.querySelector('input[placeholder="Value..."]')) {
+ throw new Error('Value input not found')
+ }
+ })
+
+ // Fill the condition value
+ const valueInput = document.querySelector<HTMLInputElement>('input[placeholder="Value..."]')!
+ await userEvent.clear(valueInput)
+ await userEvent.paste('$autocapture')
+
+ // Add a test case
+ Array.from(document.querySelectorAll('button'))
+ .find((b) => b.textContent?.trim() === 'Add test case')!
+ .click()
+
+ // Wait for test case input
+ await waitFor(() => {
+ if (!document.querySelector('input[placeholder="$pageview"]')) {
+ throw new Error('Event input not found')
+ }
+ })
+
+ // Fill test case event name
+ const eventInput = document.querySelector<HTMLInputElement>('input[placeholder="$pageview"]')!
+ await userEvent.clear(eventInput)
+ await userEvent.paste('$autocapture')
+ },
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.tsx b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.tsx
new file mode 100644
index 000000000000..ee74d9e8f82e
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.tsx
@@ -0,0 +1,277 @@
+import {
+ DndContext,
+ DragEndEvent,
+ DragOverlay,
+ DragStartEvent,
+ MouseSensor,
+ TouchSensor,
+ pointerWithin,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core'
+import { arrayMove } from '@dnd-kit/sortable'
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+import { useCallback, useMemo, useRef, useState } from 'react'
+
+import { LemonBanner, LemonButton, LemonDivider, LemonLabel, LemonModal, LemonSegmentedButton } from '@posthog/lemon-ui'
+
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { eventFilterLogic, EVENT_FILTER_MAX_CONDITIONS, EVENT_FILTER_MAX_DEPTH } from './eventFilterLogic'
+import { EventFilterMetrics } from './EventFilterMetrics'
+import { EventFilterTestCases } from './EventFilterTestCases'
+import { NodeEditor } from './EventFilterTreeEditor'
+import { filterTreeToExpression, isTreeEmpty, nodeSummary } from './filterTreeDisplay'
+import { moveBetweenGroups, reorderWithinGroup, resolveDropTarget } from './filterTreeDnd'
+import { getNodeAtPath, isAncestorPath, splitParentChild } from './filterTreePath'
+import { NodeIdMap } from './NodeIdMap'
+
+export const scene: SceneExport = {
+ component: EventFilterScene,
+ logic: eventFilterLogic,
+}
+
+export function EventFilterScene(): JSX.Element {
+ const { filterForm, isFilterFormSubmitting, allTestsPass, filterFormErrors, showFilterFormErrors } =
+ useValues(eventFilterLogic)
+ const { setFilterFormValue, submitFilterForm, updateTreeNode } = useActions(eventFilterLogic)
+ const [activeId, setActiveId] = useState<string | null>(null)
+ const [showExpression, setShowExpression] = useState(false)
+ const nodeIds = useRef(new NodeIdMap()).current
+
+ // Build nid → path index on every render (also assigns IDs to new nodes)
+ useMemo(() => nodeIds.buildIndex(filterForm.filter_tree), [filterForm.filter_tree, nodeIds])
+
+ const sensors = useSensors(
+ useSensor(MouseSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } })
+ )
+
+ const handleDragStart = useCallback((event: DragStartEvent) => {
+ setActiveId(String(event.active.id))
+ }, [])
+
+ const handleDragEnd = useCallback(
+ (event: DragEndEvent) => {
+ setActiveId(null)
+ const { active, over } = event
+ if (!over || active.id === over.id) {
+ return
+ }
+
+ const overIdStr = String(over.id)
+ const tree = filterForm.filter_tree
+ nodeIds.buildIndex(tree)
+
+ const activePath = nodeIds.pathOf(String(active.id))
+ if (!activePath) {
+ return
+ }
+ const activeParent = splitParentChild(activePath)
+ if (!activeParent) {
+ return
+ }
+
+ const target = resolveDropTarget(overIdStr, tree, nodeIds)
+ if (!target) {
+ return
+ }
+ if (isAncestorPath(activePath, target.groupPath)) {
+ return
+ }
+
+ const sameGroup = activeParent.parentPath.join('.') === target.groupPath.join('.')
+
+ if (sameGroup) {
+ const reorderedGroup = reorderWithinGroup(
+ tree,
+ activeParent.parentPath,
+ activeParent.childIndex,
+ target.insertIndex,
+ arrayMove
+ )
+ if (reorderedGroup) {
+ updateTreeNode(activeParent.parentPath, reorderedGroup)
+ }
+ } else {
+ const destGroup = target.groupPath.length === 0 ? tree : getNodeAtPath(tree, target.groupPath)
+ if (!destGroup) {
+ return
+ }
+ const destGroupNid = nodeIds.nidOf(destGroup)
+ const newTree = moveBetweenGroups(
+ tree,
+ activeParent.parentPath,
+ activeParent.childIndex,
+ destGroupNid,
+ target.insertIndex,
+ nodeIds
+ )
+ if (newTree) {
+ setFilterFormValue('filter_tree', newTree)
+ }
+ }
+ },
+ [filterForm.filter_tree, updateTreeNode, setFilterFormValue]
+ )
+
+ const activeNode = activeId ? getNodeAtPath(filterForm.filter_tree, nodeIds.pathOf(activeId) ?? []) : null
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Event ingestion filtering"
+ description="Drop events at ingestion time based on event name or distinct ID."
+ resourceType={{ type: 'data_pipeline' }}
+ />
+ <Form logic={eventFilterLogic} formKey="filterForm" enableFormOnSubmit>
+ <div className="space-y-4">
+ <LemonBanner type="info">
+ <p className="mb-1">
+ Event ingestion filtering is the most efficient way to drop unwanted events. Filters are
+ evaluated early in the ingestion pipeline, before transformations run.
+ </p>
+ <p className="mb-0">
+ Events that pass these filters will still go through any active{' '}
+ <strong>transformations</strong>, which can also drop or modify events. Use event filters
+ for simple drop rules based on event name or distinct ID, and only use transformations when
+ you need more complex logic.
+ </p>
+ </LemonBanner>
+
+ <div
+ className={`border rounded p-3 flex items-center justify-between ${
+ filterForm.mode === 'live'
+ ? 'border-success'
+ : filterForm.mode === 'dry_run'
+ ? 'border-warning'
+ : ''
+ }`}
+ >
+ <div>
+ <div className="font-semibold">
+ {filterForm.mode === 'live'
+ ? 'Filter is active'
+ : filterForm.mode === 'dry_run'
+ ? 'Filter is in dry run'
+ : 'Filter is disabled'}
+ </div>
+ <div className="text-muted text-sm">
+ {filterForm.mode === 'live'
+ ? 'Matching events are being dropped from ingestion.'
+ : filterForm.mode === 'dry_run'
+ ? 'Matching events are counted but not dropped. Use this to verify your filter before going live.'
+ : 'No events are being filtered or counted.'}
+ </div>
+ {filterForm.mode === 'live' && !allTestsPass && filterForm.test_cases.length > 0 && (
+ <div className="text-danger text-xs mt-1">Tests failing — will be saved as dry run</div>
+ )}
+ </div>
+ <LemonSegmentedButton
+ size="small"
+ options={[
+ { value: 'disabled', label: 'Disabled' },
+ { value: 'dry_run', label: 'Dry run' },
+ {
+ value: 'live',
+ label: 'Live',
+ disabledReason:
+ !allTestsPass && filterForm.test_cases.length > 0
+ ? 'All test cases must pass before going live'
+ : undefined,
+ },
+ ]}
+ value={filterForm.mode}
+ onChange={(value) => setFilterFormValue('mode', value)}
+ />
+ </div>
+
+ <EventFilterMetrics filterId={filterForm.id} />
+
+ <div className="space-y-2">
+ <div className="flex items-start justify-between">
+ <div>
+ <LemonLabel>Drop events matching</LemonLabel>
+ <p className="text-muted text-sm mb-0">
+ Build a filter expression. Drag conditions and groups to reorder or move between
+ groups. Maximum {EVENT_FILTER_MAX_CONDITIONS} conditions and{' '}
+ {EVENT_FILTER_MAX_DEPTH} levels of nesting. Empty groups are removed automatically
+ on save.
+ </p>
+ </div>
+ <LemonButton
+ size="small"
+ type="secondary"
+ className="ml-2 shrink-0"
+ onClick={() => setShowExpression(true)}
+ >
+ Show as ASCII
+ </LemonButton>
+ </div>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={pointerWithin}
+ onDragStart={handleDragStart}
+ onDragEnd={handleDragEnd}
+ >
+ <div className="border rounded p-3">
+ <NodeEditor
+ node={filterForm.filter_tree}
+ path={[]}
+ depth={0}
+ showValidation={showFilterFormErrors}
+ nodeIds={nodeIds}
+ />
+ </div>
+ {showFilterFormErrors && filterFormErrors.mode && (
+ <LemonBanner type="error">{filterFormErrors.mode}</LemonBanner>
+ )}
+ <DragOverlay>
+ {activeNode ? (
+ <div className="bg-bg-light border rounded px-3 py-1 shadow-md text-sm">
+ {nodeSummary(activeNode)}
+ </div>
+ ) : null}
+ </DragOverlay>
+ </DndContext>
+ <LemonModal
+ isOpen={showExpression}
+ onClose={() => setShowExpression(false)}
+ title="Filter tree"
+ description="Events matching this expression will be dropped."
+ >
+ <pre className="font-mono text-sm whitespace-pre-wrap p-3 border rounded bg-bg-light overflow-auto max-h-96">
+ {isTreeEmpty(filterForm.filter_tree)
+ ? '(no conditions configured)'
+ : filterTreeToExpression(filterForm.filter_tree)}
+ </pre>
+ </LemonModal>
+ </div>
+
+ <LemonDivider />
+
+ <EventFilterTestCases />
+
+ <LemonDivider />
+
+ {!allTestsPass && filterForm.mode === 'live' && (
+ <LemonBanner type="warning">
+ Some test cases are failing. The filter cannot go live until all tests pass. You can save
+ with tests failing, but the filter will be saved in dry run mode.
+ </LemonBanner>
+ )}
+
+ <div className="flex gap-2">
+ <LemonButton type="primary" onClick={() => submitFilterForm()} loading={isFilterFormSubmitting}>
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ </Form>
+ </SceneContent>
+ )
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterTestCases.tsx b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterTestCases.tsx
new file mode 100644
index 000000000000..216bad30cc10
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterTestCases.tsx
@@ -0,0 +1,108 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlusSmall, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonLabel, LemonSelect, LemonTag } from '@posthog/lemon-ui'
+
+import { eventFilterLogic, TestCase, TestResult } from './eventFilterLogic'
+
+export function EventFilterTestCases(): JSX.Element {
+ const { filterForm, testResults, allTestsPass } = useValues(eventFilterLogic)
+ const { addTestCase, removeTestCase, updateTestCase } = useActions(eventFilterLogic)
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <LemonLabel>Test cases</LemonLabel>
+ {filterForm.test_cases.length > 0 && (
+ <LemonTag type={allTestsPass ? 'success' : 'danger'}>
+ {allTestsPass
+ ? `All ${filterForm.test_cases.length} tests pass`
+ : `${testResults.filter((r: TestResult) => !r.pass).length} of ${filterForm.test_cases.length} failing`}
+ </LemonTag>
+ )}
+ </div>
+ <p className="text-muted text-sm">
+ Add test events to verify your filter. Each test specifies whether the event should be dropped or
+ ingested. The filter cannot be enabled until all tests pass.
+ </p>
+
+ {filterForm.test_cases.length > 0 && (
+ <div className="space-y-2">
+ {filterForm.test_cases.map((tc: TestCase, i: number) => {
+ const result = testResults[i]
+ return (
+ <div
+ key={tc._key}
+ className={`border rounded font-mono text-sm ${
+ result && !result.pass ? 'border-danger' : ''
+ }`}
+ >
+ <div className="flex items-center justify-between px-3 pt-2">
+ <div className="flex items-center gap-2">
+ <LemonSelect
+ size="xsmall"
+ options={[
+ { value: 'drop', label: 'Should drop' },
+ { value: 'ingest', label: 'Should ingest' },
+ ]}
+ value={tc.expected_result}
+ onChange={(value) =>
+ updateTestCase(i, {
+ expected_result: value as 'drop' | 'ingest',
+ })
+ }
+ />
+ {result && (
+ <LemonTag type={result.pass ? 'success' : 'danger'}>
+ {result.pass ? 'Pass' : `Fail (would ${result.actual})`}
+ </LemonTag>
+ )}
+ </div>
+ <LemonButton
+ icon={<IconTrash />}
+ size="xsmall"
+ status="danger"
+ aria-label="Remove test case"
+ onClick={() => removeTestCase(i)}
+ />
+ </div>
+ <div className="px-3 pb-2 pt-1">
+ <span className="text-muted">{'{'}</span>
+ <div className="pl-4 space-y-1">
+ <div className="flex items-center gap-1">
+ <span className="text-primary">"event"</span>
+ <span className="text-muted">:</span>
+ <LemonInput
+ size="small"
+ value={tc.event_name}
+ onChange={(value) => updateTestCase(i, { event_name: value })}
+ placeholder="$pageview"
+ className="flex-1 font-mono"
+ />
+ </div>
+ <div className="flex items-center gap-1">
+ <span className="text-primary">"distinct_id"</span>
+ <span className="text-muted">:</span>
+ <LemonInput
+ size="small"
+ value={tc.distinct_id}
+ onChange={(value) => updateTestCase(i, { distinct_id: value })}
+ placeholder="user-123"
+ className="flex-1 font-mono"
+ />
+ </div>
+ </div>
+ <span className="text-muted">{'}'}</span>
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )}
+
+ <LemonButton size="small" type="secondary" icon={<IconPlusSmall />} onClick={() => addTestCase()}>
+ Add test case
+ </LemonButton>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterTreeEditor.tsx b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterTreeEditor.tsx
new file mode 100644
index 000000000000..febd15d61636
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterTreeEditor.tsx
@@ -0,0 +1,303 @@
+import { useDroppable, useDndMonitor } from '@dnd-kit/core'
+import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
+import { useActions, useValues } from 'kea'
+import React, { useState } from 'react'
+
+import { IconPlusSmall, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'
+
+import { IconDragHandle } from 'lib/lemon-ui/icons'
+
+import {
+ EVENT_FILTER_MAX_CONDITIONS,
+ EVENT_FILTER_MAX_DEPTH,
+ eventFilterLogic,
+ FilterNode,
+ TreePath,
+} from './eventFilterLogic'
+import { NodeIdMap } from './NodeIdMap'
+
+const FIELD_OPTIONS = [
+ { value: 'event_name', label: 'Event name' },
+ { value: 'distinct_id', label: 'Distinct ID' },
+]
+
+const OPERATOR_OPTIONS = [
+ { value: 'exact', label: 'equals' },
+ { value: 'contains', label: 'contains' },
+]
+
+export function SortableItem({ id, children }: { id: string; children: React.ReactNode }): JSX.Element {
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id })
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ opacity: isDragging ? 0.3 : 1,
+ }
+ return (
+ <div ref={setNodeRef} style={style} className="flex items-start gap-1">
+ <div className="mt-2 cursor-grab text-muted hover:text-default shrink-0" {...attributes} {...listeners}>
+ <IconDragHandle />
+ </div>
+ <div className="flex-1 min-w-0">{children}</div>
+ </div>
+ )
+}
+
+function ConditionEditor({
+ node,
+ path,
+ onDelete,
+ showValidation,
+}: {
+ node: FilterNode & { type: 'condition' }
+ path: TreePath
+ onDelete?: () => void
+ showValidation?: boolean
+}): JSX.Element {
+ const { updateTreeNode } = useActions(eventFilterLogic)
+ const isEmpty = showValidation && (!node.value || node.value.trim() === '')
+ return (
+ <div className="flex items-center gap-2 py-1">
+ <LemonSelect
+ size="small"
+ options={FIELD_OPTIONS}
+ value={node.field}
+ onChange={(value) => updateTreeNode(path, { ...node, field: value as typeof node.field })}
+ />
+ <LemonSelect
+ size="small"
+ options={OPERATOR_OPTIONS}
+ value={node.operator}
+ onChange={(value) => updateTreeNode(path, { ...node, operator: value as typeof node.operator })}
+ />
+ <LemonInput
+ size="small"
+ value={node.value}
+ onChange={(value) => updateTreeNode(path, { ...node, value })}
+ placeholder="Value..."
+ className="flex-1"
+ status={isEmpty ? 'danger' : undefined}
+ />
+ {onDelete && (
+ <LemonButton
+ icon={<IconTrash />}
+ size="xsmall"
+ status="danger"
+ onClick={onDelete}
+ tooltip="Remove"
+ aria-label="Remove"
+ data-attr={`remove-${path.length === 0 ? 'root' : path.join('-')}`}
+ />
+ )}
+ </div>
+ )
+}
+
+function GroupEditor({
+ node,
+ path,
+ depth,
+ onDelete,
+ showValidation,
+ nodeIds,
+}: {
+ node: FilterNode & { type: 'and' | 'or' }
+ path: TreePath
+ depth: number
+ onDelete?: () => void
+ showValidation?: boolean
+ nodeIds: NodeIdMap
+}): JSX.Element {
+ const { updateTreeNode, removeChild, wrapInNot, addChild } = useActions(eventFilterLogic)
+ const { conditionCount } = useValues(eventFilterLogic)
+
+ // A new condition adds a leaf at depth+1; a new group adds itself at depth+1
+ // with a leaf at depth+2. Both must satisfy the backend's max_depth ≤ N rule.
+ const maxConditionsReason =
+ conditionCount >= EVENT_FILTER_MAX_CONDITIONS
+ ? `Maximum of ${EVENT_FILTER_MAX_CONDITIONS} conditions reached`
+ : undefined
+ const maxDepthReason = `Maximum nesting depth of ${EVENT_FILTER_MAX_DEPTH} reached`
+ const addConditionDisabledReason =
+ maxConditionsReason ?? (depth >= EVENT_FILTER_MAX_DEPTH ? maxDepthReason : undefined)
+ const addGroupDisabledReason =
+ maxConditionsReason ?? (depth >= EVENT_FILTER_MAX_DEPTH - 1 ? maxDepthReason : undefined)
+
+ const pathAttr = path.length === 0 ? 'root' : path.join('-')
+ const droppableId = `drop:${nodeIds.nidOf(node)}`
+ const { setNodeRef, isOver } = useDroppable({ id: droppableId })
+ const borderColor = node.type === 'and' ? 'bg-[#2563EB]' : 'bg-[#F59E0B]'
+
+ const childNids = node.children.map((child) => nodeIds.nidOf(child))
+
+ // Track whether the drag is over this group's droppable zone or any
+ // of its direct children (including items dragged from other groups).
+ // useDndMonitor fires on ALL groups simultaneously, so each group checks
+ // if the over target belongs to it and only updates its own state.
+ const [isOverGroup, setIsOverGroup] = useState(false)
+ useDndMonitor({
+ onDragOver(event) {
+ const overId = event.over ? String(event.over.id) : undefined
+ const isMatch = overId === droppableId || (!!overId && childNids.includes(overId))
+ setIsOverGroup(isMatch)
+ },
+ onDragEnd() {
+ setIsOverGroup(false)
+ },
+ onDragCancel() {
+ setIsOverGroup(false)
+ },
+ })
+
+ const shouldHighlight = isOver || isOverGroup
+
+ return (
+ <div ref={setNodeRef} className={`flex gap-0 ${shouldHighlight ? 'bg-fill-highlight rounded' : ''}`}>
+ <div className={`w-0.5 shrink-0 rounded ${borderColor}`} />
+ <div className="flex-1 min-w-0 py-1 pl-2 space-y-1">
+ <div className="flex items-center gap-2">
+ <LemonSelect
+ size="xsmall"
+ options={[
+ { value: 'and', label: 'AND' },
+ { value: 'or', label: 'OR' },
+ ]}
+ value={node.type}
+ onChange={(value) =>
+ updateTreeNode(path, { type: value as 'and' | 'or', children: node.children })
+ }
+ />
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ data-attr={`negate-${pathAttr}`}
+ onClick={() => wrapInNot(path)}
+ >
+ Negate
+ </LemonButton>
+ {onDelete && (
+ <LemonButton
+ icon={<IconTrash />}
+ size="xsmall"
+ status="danger"
+ onClick={onDelete}
+ tooltip="Remove"
+ aria-label="Remove"
+ data-attr={`remove-${pathAttr}`}
+ />
+ )}
+ </div>
+
+ <SortableContext items={childNids} strategy={verticalListSortingStrategy}>
+ {node.children.map((child, i) => {
+ const childPath: TreePath = [...path, i]
+ const childId = nodeIds.nidOf(child)
+ return (
+ <SortableItem key={childId} id={childId}>
+ <NodeEditor
+ node={child}
+ path={childPath}
+ depth={depth + 1}
+ onDelete={() => removeChild(path, i)}
+ showValidation={showValidation}
+ nodeIds={nodeIds}
+ />
+ </SortableItem>
+ )
+ })}
+ </SortableContext>
+
+ <div className="flex gap-2">
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconPlusSmall />}
+ data-attr={`add-condition-${pathAttr}`}
+ onClick={() => addChild(path)}
+ disabledReason={addConditionDisabledReason}
+ >
+ Add condition
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconPlusSmall />}
+ data-attr={`add-group-${pathAttr}`}
+ onClick={() => {
+ const newGroup: FilterNode = {
+ type: 'and',
+ children: [{ type: 'condition', field: 'event_name', operator: 'exact', value: '' }],
+ }
+ updateTreeNode(path, { ...node, children: [...node.children, newGroup] })
+ }}
+ disabledReason={addGroupDisabledReason}
+ >
+ Add group
+ </LemonButton>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export function NodeEditor({
+ node,
+ path,
+ depth,
+ onDelete,
+ showValidation,
+ nodeIds,
+}: {
+ node: FilterNode
+ path: TreePath
+ depth: number
+ onDelete?: () => void
+ showValidation?: boolean
+ nodeIds: NodeIdMap
+}): JSX.Element {
+ const { unwrapNot } = useActions(eventFilterLogic)
+
+ if (node.type === 'condition') {
+ return <ConditionEditor node={node} path={path} onDelete={onDelete} showValidation={showValidation} />
+ }
+ if (node.type === 'not') {
+ return (
+ <div className="border-l-2 border-danger pl-3 py-1 space-y-1">
+ <div className="flex items-center gap-2">
+ <span className="text-danger font-semibold text-xs">NOT</span>
+ <LemonButton size="xsmall" status="danger" onClick={() => unwrapNot(path)}>
+ Remove NOT
+ </LemonButton>
+ {onDelete && (
+ <LemonButton
+ icon={<IconTrash />}
+ size="xsmall"
+ status="danger"
+ onClick={onDelete}
+ tooltip="Remove"
+ />
+ )}
+ </div>
+ <NodeEditor
+ node={node.child}
+ path={[...path, 'child']}
+ depth={depth + 1}
+ showValidation={showValidation}
+ nodeIds={nodeIds}
+ />
+ </div>
+ )
+ }
+ return (
+ <GroupEditor
+ node={node}
+ path={path}
+ depth={depth}
+ onDelete={onDelete}
+ showValidation={showValidation}
+ nodeIds={nodeIds}
+ />
+ )
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/NodeIdMap.test.ts b/frontend/src/scenes/data-pipelines/event-filtering/NodeIdMap.test.ts
new file mode 100644
index 000000000000..ea1d94fd4cee
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/NodeIdMap.test.ts
@@ -0,0 +1,94 @@
+import { NodeIdMap } from './NodeIdMap'
+import { cond, and, or, not } from './testHelpers'
+
+describe('NodeIdMap', () => {
+ describe('nidOf', () => {
+ it('assigns a non-empty string ID', () => {
+ const nodeIds = new NodeIdMap()
+ expect(nodeIds.nidOf(cond())).not.toBe('')
+ })
+
+ it('returns the same ID for the same object reference', () => {
+ const nodeIds = new NodeIdMap()
+ const node = cond()
+ expect(nodeIds.nidOf(node)).toBe(nodeIds.nidOf(node))
+ })
+
+ it('returns different IDs for different objects', () => {
+ const nodeIds = new NodeIdMap()
+ expect(nodeIds.nidOf(cond())).not.toBe(nodeIds.nidOf(cond()))
+ })
+
+ it('preserves IDs across buildIndex calls', () => {
+ const nodeIds = new NodeIdMap()
+ const node = cond()
+ const tree = or(node)
+ nodeIds.buildIndex(tree)
+ const first = nodeIds.nidOf(node)
+ nodeIds.buildIndex(tree)
+ expect(nodeIds.nidOf(node)).toBe(first)
+ })
+ })
+
+ describe('buildIndex and pathOf', () => {
+ it('indexes a single condition at root', () => {
+ const nodeIds = new NodeIdMap()
+ const tree = cond()
+ nodeIds.buildIndex(tree)
+ expect(nodeIds.pathOf(nodeIds.nidOf(tree))).toEqual([])
+ })
+
+ it('indexes AND/OR children with numeric paths', () => {
+ const nodeIds = new NodeIdMap()
+ const c0 = cond('event_name', 'exact', 'a')
+ const c1 = cond('event_name', 'exact', 'b')
+ const tree = or(c0, c1)
+ nodeIds.buildIndex(tree)
+
+ expect(nodeIds.pathOf(nodeIds.nidOf(tree))).toEqual([])
+ expect(nodeIds.pathOf(nodeIds.nidOf(c0))).toEqual([0])
+ expect(nodeIds.pathOf(nodeIds.nidOf(c1))).toEqual([1])
+ })
+
+ it('indexes NOT child with "child" step', () => {
+ const nodeIds = new NodeIdMap()
+ const inner = cond()
+ const tree = not(inner)
+ nodeIds.buildIndex(tree)
+
+ expect(nodeIds.pathOf(nodeIds.nidOf(tree))).toEqual([])
+ expect(nodeIds.pathOf(nodeIds.nidOf(inner))).toEqual(['child'])
+ })
+
+ it('indexes a deep tree', () => {
+ const nodeIds = new NodeIdMap()
+ const leaf = cond()
+ const tree = and(or(leaf, cond()), not(cond()))
+ nodeIds.buildIndex(tree)
+
+ expect(nodeIds.pathOf(nodeIds.nidOf(leaf))).toEqual([0, 0])
+ })
+
+ it('returns undefined for unknown nid', () => {
+ const nodeIds = new NodeIdMap()
+ nodeIds.buildIndex(cond())
+ expect(nodeIds.pathOf('nonexistent')).toBeUndefined()
+ })
+
+ it('rebuilds index correctly after tree mutation', () => {
+ const nodeIds = new NodeIdMap()
+ const c0 = cond('event_name', 'exact', 'a')
+ const c1 = cond('event_name', 'exact', 'b')
+ const tree1 = or(c0, c1)
+ nodeIds.buildIndex(tree1)
+ expect(nodeIds.pathOf(nodeIds.nidOf(c0))).toEqual([0])
+
+ // Simulate removing c0 — c1 is now at index 0
+ const tree2 = or(c1)
+ nodeIds.buildIndex(tree2)
+ expect(nodeIds.pathOf(nodeIds.nidOf(c1))).toEqual([0])
+ // c0 is no longer in the index
+ expect(nodeIds.pathOf(nodeIds.nidOf(c0))).toBeUndefined()
+ })
+ })
+})
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/NodeIdMap.ts b/frontend/src/scenes/data-pipelines/event-filtering/NodeIdMap.ts
new file mode 100644
index 000000000000..a2b46d411ec9
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/NodeIdMap.ts
@@ -0,0 +1,56 @@
+import type { FilterNode, TreePath } from './eventFilterLogic'
+
+/**
+ * Maps FilterNode object references to stable string IDs for DnD.
+ *
+ * DnD needs stable IDs for each node. Array indices don't work because they
+ * shift when siblings are added/removed/reordered. NodeIdMap assigns each
+ * node a stable string ID via a WeakMap keyed by object identity. Since
+ * updateAtPath uses structural sharing (unchanged subtrees keep their
+ * references), IDs survive across tree mutations automatically.
+ *
+ * The instance is owned by the scene component (via useRef) and passed
+ * down to the tree editor. This avoids module-level global state.
+ */
+
+let nidCounter = 0
+
+export class NodeIdMap {
+ private ids = new WeakMap<FilterNode, string>()
+ private pathIndex: Map<string, TreePath> = new Map()
+
+ /** Get or assign a stable ID for a node. */
+ nidOf(node: FilterNode): string {
+ let id = this.ids.get(node)
+ if (!id) {
+ id = `n${nidCounter++}`
+ this.ids.set(node, id)
+ }
+ return id
+ }
+
+ /**
+ * Rebuild the nid → TreePath index for the given tree.
+ * Call this once per render before using pathOf().
+ */
+ buildIndex(node: FilterNode): void {
+ this.pathIndex = new Map()
+ this.indexNode(node, [])
+ }
+
+ private indexNode(node: FilterNode, path: TreePath): void {
+ this.pathIndex.set(this.nidOf(node), path)
+ if (node.type === 'and' || node.type === 'or') {
+ for (let i = 0; i < node.children.length; i++) {
+ this.indexNode(node.children[i], [...path, i])
+ }
+ } else if (node.type === 'not') {
+ this.indexNode(node.child, [...path, 'child'])
+ }
+ }
+
+ /** Look up the TreePath for a given nid, or undefined if not in the current index. */
+ pathOf(nid: string): TreePath | undefined {
+ return this.pathIndex.get(nid)
+ }
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.test.ts b/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.test.ts
new file mode 100644
index 000000000000..df06b1f90903
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.test.ts
@@ -0,0 +1,316 @@
+import {
+ countConditions,
+ evaluateFilterTree,
+ FilterNode,
+ treeHasConditions,
+ treeHasEmptyValues,
+ updateAtPath,
+} from './eventFilterLogic'
+import { cond, and, or, not } from './testHelpers'
+
+describe('evaluateFilterTree', () => {
+ describe('condition nodes', () => {
+ it.each([
+ ['exact match', cond('event_name', 'exact', 'pageview'), { event_name: 'pageview' }, true],
+ ['exact no match', cond('event_name', 'exact', 'pageview'), { event_name: 'click' }, false],
+ ['contains match', cond('event_name', 'contains', 'view'), { event_name: 'pageview' }, true],
+ ['contains no match', cond('event_name', 'contains', 'click'), { event_name: 'pageview' }, false],
+ ['missing field', cond('event_name', 'exact', 'pageview'), {}, false],
+ ['distinct_id match', cond('distinct_id', 'exact', 'u1'), { distinct_id: 'u1' }, true],
+ ['empty string field matches empty value', cond('event_name', 'exact', ''), { event_name: '' }, true],
+ ['empty string field contains empty', cond('event_name', 'contains', ''), { event_name: 'anything' }, true],
+ ])('%s', (_name, tree, event, expected) => {
+ expect(evaluateFilterTree(tree, event)).toBe(expected)
+ })
+ })
+
+ describe('AND nodes', () => {
+ it('all true', () => {
+ const tree = and(cond('event_name', 'exact', 'pageview'), cond('distinct_id', 'exact', 'u1'))
+ expect(evaluateFilterTree(tree, { event_name: 'pageview', distinct_id: 'u1' })).toBe(true)
+ })
+
+ it('one false', () => {
+ const tree = and(cond('event_name', 'exact', 'pageview'), cond('distinct_id', 'exact', 'u1'))
+ expect(evaluateFilterTree(tree, { event_name: 'pageview', distinct_id: 'u2' })).toBe(false)
+ })
+
+ it('empty children returns false', () => {
+ expect(evaluateFilterTree(and(), {})).toBe(false)
+ })
+ })
+
+ describe('OR nodes', () => {
+ it('one true', () => {
+ const tree = or(cond('event_name', 'exact', 'pageview'), cond('event_name', 'exact', 'click'))
+ expect(evaluateFilterTree(tree, { event_name: 'click' })).toBe(true)
+ })
+
+ it('none true', () => {
+ const tree = or(cond('event_name', 'exact', 'pageview'), cond('event_name', 'exact', 'click'))
+ expect(evaluateFilterTree(tree, { event_name: 'submit' })).toBe(false)
+ })
+
+ it('empty children returns false', () => {
+ expect(evaluateFilterTree(or(), {})).toBe(false)
+ })
+ })
+
+ describe('NOT nodes', () => {
+ it('inverts true to false', () => {
+ expect(evaluateFilterTree(not(cond('event_name', 'exact', 'pageview')), { event_name: 'pageview' })).toBe(
+ false
+ )
+ })
+
+ it('inverts false to true', () => {
+ expect(evaluateFilterTree(not(cond('event_name', 'exact', 'pageview')), { event_name: 'click' })).toBe(true)
+ })
+ })
+
+ describe('complex tree', () => {
+ // Drop if: (event is "$autocapture" OR event contains "bot_")
+ // AND NOT (distinct_id is "admin-user")
+ const tree = and(
+ or(cond('event_name', 'exact', '$autocapture'), cond('event_name', 'contains', 'bot_')),
+ not(cond('distinct_id', 'exact', 'admin-user'))
+ )
+
+ it.each([
+ ['$autocapture from regular user -> drop', { event_name: '$autocapture', distinct_id: 'user-1' }, true],
+ ['bot_ event from regular user -> drop', { event_name: 'bot_heartbeat', distinct_id: 'user-2' }, true],
+ ['$autocapture from admin -> ingest', { event_name: '$autocapture', distinct_id: 'admin-user' }, false],
+ ['bot_ event from admin -> ingest', { event_name: 'bot_ping', distinct_id: 'admin-user' }, false],
+ ['normal event from regular user -> ingest', { event_name: 'purchase', distinct_id: 'user-1' }, false],
+ ['normal event from admin -> ingest', { event_name: 'login', distinct_id: 'admin-user' }, false],
+ [
+ 'partial match on bot_ via contains -> drop',
+ { event_name: 'internal_bot_check', distinct_id: 'service-1' },
+ true,
+ ],
+ ['event_name missing -> ingest', { distinct_id: 'user-1' }, false],
+ ['distinct_id missing -> drop', { event_name: '$autocapture' }, true],
+ ])('%s', (_name, event, expected) => {
+ expect(evaluateFilterTree(tree, event)).toBe(expected)
+ })
+ })
+
+ describe('double negation', () => {
+ it('NOT(NOT(condition)) evaluates to the original condition result', () => {
+ const tree = not(not(cond('event_name', 'exact', 'pageview')))
+ expect(evaluateFilterTree(tree, { event_name: 'pageview' })).toBe(true)
+ expect(evaluateFilterTree(tree, { event_name: 'click' })).toBe(false)
+ })
+ })
+
+ describe('deeply nested tree (4 levels)', () => {
+ // OR(AND(NOT(condition), condition), condition)
+ const tree = or(
+ and(not(cond('event_name', 'contains', 'internal')), cond('distinct_id', 'contains', 'bot')),
+ cond('event_name', 'exact', '$drop_me')
+ )
+
+ it.each([
+ ['matches second OR branch', { event_name: '$drop_me', distinct_id: 'user-1' }, true],
+ ['matches first OR branch (not internal + bot)', { event_name: 'ping', distinct_id: 'bot-1' }, true],
+ ['blocked by NOT (internal + bot)', { event_name: 'internal_check', distinct_id: 'bot-1' }, false],
+ ['no match at all', { event_name: 'click', distinct_id: 'user-1' }, false],
+ ])('%s', (_name, event, expected) => {
+ expect(evaluateFilterTree(tree, event)).toBe(expected)
+ })
+ })
+})
+
+describe('updateAtPath', () => {
+ const replacement = cond('distinct_id', 'exact', 'replaced')
+
+ describe('root updates (empty path)', () => {
+ it('replaces the entire tree', () => {
+ const tree = cond()
+ const result = updateAtPath(tree, [], () => replacement)
+ expect(result).toEqual(replacement)
+ })
+
+ it('wraps root in NOT', () => {
+ const tree = cond()
+ const result = updateAtPath(tree, [], (node) => not(node))
+ expect(result).toEqual(not(cond()))
+ })
+
+ it('converts root condition to a group', () => {
+ const tree = cond()
+ const result = updateAtPath(tree, [], (node) => and(node))
+ expect(result).toEqual(and(cond()))
+ })
+ })
+
+ describe('updating children in AND/OR groups', () => {
+ it('updates first child of an OR group', () => {
+ const tree = or(cond('event_name', 'exact', 'a'), cond('event_name', 'exact', 'b'))
+ const result = updateAtPath(tree, [0], () => replacement)
+ expect(result).toEqual(or(replacement, cond('event_name', 'exact', 'b')))
+ })
+
+ it('updates second child of an AND group', () => {
+ const tree = and(cond('event_name', 'exact', 'a'), cond('event_name', 'exact', 'b'))
+ const result = updateAtPath(tree, [1], () => replacement)
+ expect(result).toEqual(and(cond('event_name', 'exact', 'a'), replacement))
+ })
+
+ it('adds a child to a group via updater', () => {
+ const tree = or(cond())
+ const result = updateAtPath(tree, [], (node) => {
+ if (node.type === 'or') {
+ return { ...node, children: [...node.children, replacement] }
+ }
+ return node
+ })
+ expect(result).toEqual(or(cond(), replacement))
+ })
+
+ it('removes a child from a group via updater', () => {
+ const tree = and(cond('event_name', 'exact', 'a'), cond('event_name', 'exact', 'b'))
+ const result = updateAtPath(tree, [], (node) => {
+ if (node.type === 'and') {
+ return { ...node, children: node.children.filter((_, i) => i !== 0) }
+ }
+ return node
+ })
+ expect(result).toEqual(and(cond('event_name', 'exact', 'b')))
+ })
+ })
+
+ describe('updating through NOT nodes', () => {
+ it('updates the child of a NOT node', () => {
+ const tree = not(cond())
+ const result = updateAtPath(tree, ['child'], () => replacement)
+ expect(result).toEqual(not(replacement))
+ })
+
+ it('unwraps a NOT by returning its child', () => {
+ const inner = cond()
+ const tree = not(inner)
+ const result = updateAtPath(tree, [], (node) => {
+ if (node.type === 'not') {
+ return node.child
+ }
+ return node
+ })
+ expect(result).toEqual(inner)
+ })
+ })
+
+ describe('deep nested paths', () => {
+ // AND(OR(condA, condB), NOT(condC))
+ const condA = cond('event_name', 'exact', 'a')
+ const condB = cond('event_name', 'exact', 'b')
+ const condC = cond('distinct_id', 'exact', 'c')
+ const tree = and(or(condA, condB), not(condC))
+
+ it('updates condA at [0, 0]', () => {
+ const result = updateAtPath(tree, [0, 0], () => replacement)
+ expect(result).toEqual(and(or(replacement, condB), not(condC)))
+ })
+
+ it('updates condB at [0, 1]', () => {
+ const result = updateAtPath(tree, [0, 1], () => replacement)
+ expect(result).toEqual(and(or(condA, replacement), not(condC)))
+ })
+
+ it('updates condC through NOT at [1, "child"]', () => {
+ const result = updateAtPath(tree, [1, 'child'], () => replacement)
+ expect(result).toEqual(and(or(condA, condB), not(replacement)))
+ })
+
+ it('wraps a nested condition in NOT', () => {
+ const result = updateAtPath(tree, [0, 0], (node) => not(node))
+ expect(result).toEqual(and(or(not(condA), condB), not(condC)))
+ })
+
+ it('replaces the OR subgroup entirely', () => {
+ const result = updateAtPath(tree, [0], () => replacement)
+ expect(result).toEqual(and(replacement, not(condC)))
+ })
+ })
+
+ describe('edge cases', () => {
+ it('out-of-bounds index returns node unchanged', () => {
+ const tree = or(cond())
+ const result = updateAtPath(tree, [5], () => replacement)
+ expect(result).toEqual(tree)
+ })
+
+ it('numeric step on NOT node returns node unchanged', () => {
+ const tree = not(cond())
+ const result = updateAtPath(tree, [0], () => replacement)
+ expect(result).toEqual(tree)
+ })
+
+ it('"child" step on group node returns node unchanged', () => {
+ const tree = and(cond())
+ const result = updateAtPath(tree, ['child'], () => replacement)
+ expect(result).toEqual(tree)
+ })
+ })
+
+ describe('immutability', () => {
+ it('does not mutate the original tree', () => {
+ const tree = and(cond('event_name', 'exact', 'a'), cond('event_name', 'exact', 'b'))
+ const original = JSON.parse(JSON.stringify(tree))
+ updateAtPath(tree, [0], () => replacement)
+ expect(tree).toEqual(original)
+ })
+
+ it('shares unchanged subtrees by reference', () => {
+ const child0 = cond('event_name', 'exact', 'a')
+ const child1 = cond('event_name', 'exact', 'b')
+ const tree = or(child0, child1)
+ const result = updateAtPath(tree, [0], () => replacement)
+ // child1 should be the same reference — not copied
+ expect((result as { type: 'or'; children: FilterNode[] }).children[1]).toBe(child1)
+ })
+ })
+})
+
+describe('treeHasConditions', () => {
+ it.each([
+ ['bare condition', cond(), true],
+ ['nested condition', and(cond()), true],
+ ['not condition', not(cond()), true],
+ ['empty and', and(), false],
+ ['empty or', or(), false],
+ ['not with empty child', not(or()), false],
+ ])('%s', (_name, tree, expected) => {
+ expect(treeHasConditions(tree)).toBe(expected)
+ })
+})
+
+describe('countConditions', () => {
+ it.each([
+ ['bare condition', cond(), 1],
+ ['empty and', and(), 0],
+ ['empty or', or(), 0],
+ ['flat or of three', or(cond(), cond(), cond()), 3],
+ ['nested and inside or', or(cond(), and(cond(), cond())), 3],
+ ['not wrapping condition', not(cond()), 1],
+ ['not wrapping empty group', not(or()), 0],
+ ['deeply nested', and(or(cond(), not(cond())), and(cond())), 3],
+ ])('%s', (_name, tree, expected) => {
+ expect(countConditions(tree)).toBe(expected)
+ })
+})
+
+describe('treeHasEmptyValues', () => {
+ it.each([
+ ['filled condition', cond('event_name', 'exact', 'pageview'), false],
+ ['empty value', cond('event_name', 'exact', ''), true],
+ ['whitespace only', cond('event_name', 'exact', ' '), true],
+ ['nested empty in and', and(cond(), cond('event_name', 'exact', '')), true],
+ ['nested empty in not', not(cond('event_name', 'exact', '')), true],
+ ['all filled in group', and(cond(), cond('distinct_id', 'exact', 'u1')), false],
+ ['empty group has no empty values', or(), false],
+ ['deeply nested empty value', and(or(cond(), not(cond('event_name', 'exact', '')))), true],
+ ])('%s', (_name, tree, expected) => {
+ expect(treeHasEmptyValues(tree)).toBe(expected)
+ })
+})
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.ts b/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.ts
new file mode 100644
index 000000000000..c7698d2da4ed
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/eventFilterLogic.ts
@@ -0,0 +1,436 @@
+/**
+ * Kea logic for the event filtering scene.
+ *
+ * Manages a singleton per-team event filter config: a boolean expression tree
+ * that determines which events to drop at ingestion time.
+ *
+ * ## User actions → logic flow
+ *
+ * ### Filter tree editor
+ *
+ * The tree editor renders the filter as nested AND/OR groups with condition
+ * rows. Each group and condition receives a `path` prop (TreePath) that
+ * identifies its position in the tree.
+ *
+ * - Change field/operator/value → `updateTreeNode(path, newNode)`
+ * - Toggle AND ↔ OR → `updateTreeNode(path, { type: newType, children })`
+ * - "Add condition" → `addChild(path)`
+ * - "Add group" → `updateTreeNode(path, { ...node, children: [..., newGroup] })`
+ * - Trash icon → `removeChild(parentPath, childIndex)`
+ * - "Negate" → `wrapInNot(path)`
+ * - "Remove NOT" → `unwrapNot(path)`
+ *
+ * ### Drag and drop
+ *
+ * Users can drag conditions and groups to reorder or move between groups.
+ * DnD is handled in the scene component using @dnd-kit, not through kea actions:
+ * - Reorder within same group → arrayMove + `updateTreeNode`
+ * - Move between groups → deep-clone, splice, `setFilterFormValue`
+ * - Drop into own descendant is blocked
+ *
+ * ### Mode selector
+ *
+ * - Change disabled/dry_run/live → `setFilterFormValue('mode', value)`
+ * - Blocked from 'live' if test cases are failing
+ *
+ * ### Test cases
+ *
+ * - "Add test case" → `addTestCase()`
+ * - Edit fields → `updateTestCase(index, updates)`
+ * - Trash → `removeTestCase(index)`
+ * - Pass/fail badges update via `testResults` selector (client-side evaluation)
+ *
+ * ### Save
+ *
+ * - "Save" → `submitFilterForm()` → validation → POST to event_filter/ (upsert)
+ * - If 'live' but tests fail, auto-downgrades to 'dry_run'
+ *
+ * ## Evaluation parity
+ *
+ * evaluateFilterTree runs client-side for test case preview. Equivalent
+ * implementations exist in the Django model (validation on save) and
+ * the Node.js ingestion pipeline (runtime filtering).
+ */
+import { actions, afterMount, kea, listeners, path, selectors } from 'kea'
+import { forms } from 'kea-forms'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { Breadcrumb } from '~/types'
+
+import type { eventFilterLogicType } from './eventFilterLogicType'
+
+// Limits — must match MAX_CONDITIONS and MAX_TREE_DEPTH in posthog/models/event_filter_config.py
+export const EVENT_FILTER_MAX_CONDITIONS = 20
+export const EVENT_FILTER_MAX_DEPTH = 5
+
+// --- Filter tree types ---
+// Recursive discriminated union. Mirrors the JSON schema stored in Postgres
+// and the Zod schema in nodejs/src/ingestion/common/event-filters/schema.ts.
+
+export type FilterNode = FilterConditionNode | FilterAndNode | FilterOrNode | FilterNotNode
+
+export interface FilterConditionNode {
+ type: 'condition'
+ field: 'event_name' | 'distinct_id'
+ operator: 'exact' | 'contains'
+ value: string
+}
+
+export interface FilterAndNode {
+ type: 'and'
+ children: FilterNode[]
+}
+
+export interface FilterOrNode {
+ type: 'or'
+ children: FilterNode[]
+}
+
+export interface FilterNotNode {
+ type: 'not'
+ child: FilterNode
+}
+
+export interface TestCase {
+ _key: string
+ event_name: string
+ distinct_id: string
+ expected_result: 'drop' | 'ingest'
+}
+
+let testCaseCounter = 0
+export function nextTestCaseKey(): string {
+ return `tc${testCaseCounter++}`
+}
+
+export interface TestResult {
+ actual: 'drop' | 'ingest'
+ pass: boolean
+}
+
+export type EventFilterMode = 'disabled' | 'dry_run' | 'live'
+
+export interface EventFilterFormValues {
+ id: string | null
+ mode: EventFilterMode
+ filter_tree: FilterNode
+ test_cases: TestCase[]
+}
+
+const DEFAULT_FORM: EventFilterFormValues = {
+ id: null,
+ mode: 'disabled',
+ filter_tree: { type: 'or', children: [] },
+ test_cases: [],
+}
+
+// --- Pure functions (shared across 3 implementations) ---
+
+/**
+ * Evaluate a filter tree against a test event. Returns true if the event should be dropped.
+ *
+ * Safety: empty AND/OR groups return false (never drop). This is intentional —
+ * dropping is irreversible, so we err on the side of not dropping.
+ */
+export function evaluateFilterTree(node: FilterNode, event: Record<string, string>): boolean {
+ switch (node.type) {
+ case 'condition': {
+ const fieldValue = event[node.field]
+ if (fieldValue === undefined) {
+ return false
+ }
+ switch (node.operator) {
+ case 'exact':
+ return fieldValue === node.value
+ case 'contains':
+ return fieldValue.includes(node.value)
+ }
+ }
+ case 'and':
+ // Guard: [].every() is true in JS, which would drop everything
+ return node.children.length > 0 && node.children.every((child) => evaluateFilterTree(child, event))
+ case 'or':
+ return node.children.some((child) => evaluateFilterTree(child, event))
+ case 'not':
+ return !evaluateFilterTree(node.child, event)
+ }
+}
+
+/** Returns true if the tree contains at least one condition leaf. */
+export function treeHasConditions(node: FilterNode): boolean {
+ switch (node.type) {
+ case 'condition':
+ return true
+ case 'not':
+ return treeHasConditions(node.child)
+ case 'and':
+ case 'or':
+ return node.children.some((child) => treeHasConditions(child))
+ }
+}
+
+/** Counts the total number of condition leaves in the tree. */
+export function countConditions(node: FilterNode): number {
+ switch (node.type) {
+ case 'condition':
+ return 1
+ case 'not':
+ return countConditions(node.child)
+ case 'and':
+ case 'or':
+ return node.children.reduce((sum, child) => sum + countConditions(child), 0)
+ }
+}
+
+/** Returns true if any condition leaf has an empty or whitespace-only value. */
+export function treeHasEmptyValues(node: FilterNode): boolean {
+ switch (node.type) {
+ case 'condition':
+ return !node.value || node.value.trim() === ''
+ case 'not':
+ return treeHasEmptyValues(node.child)
+ case 'and':
+ case 'or':
+ return node.children.some((child) => treeHasEmptyValues(child))
+ }
+}
+
+// --- Immutable tree updates ---
+
+/**
+ * Path into a filter tree. Numbers index into AND/OR children arrays,
+ * 'child' navigates into a NOT node's inner child.
+ * E.g. [0, 'child', 1] = "root.children[0].child.children[1]"
+ */
+export type TreePath = ('child' | number)[]
+
+/**
+ * Immutable deep update of a filter tree node at the given path.
+ * Shallow-copies only the nodes along the path; unchanged subtrees
+ * are shared by reference. Returns the node unchanged if the path
+ * doesn't match the tree structure (e.g. numeric step on a NOT node).
+ */
+export function updateAtPath(node: FilterNode, path: TreePath, updater: (node: FilterNode) => FilterNode): FilterNode {
+ if (path.length === 0) {
+ return updater(node)
+ }
+ const [step, ...rest] = path
+ if (typeof step === 'number' && (node.type === 'and' || node.type === 'or')) {
+ return {
+ ...node,
+ children: node.children.map((child, i) => (i === step ? updateAtPath(child, rest, updater) : child)),
+ }
+ }
+ if (step === 'child' && node.type === 'not') {
+ return { ...node, child: updateAtPath(node.child, rest, updater) }
+ }
+ return node
+}
+
+// --- Kea logic ---
+
+export const eventFilterLogic = kea<eventFilterLogicType>([
+ path(['scenes', 'data-pipelines', 'event-filtering', 'eventFilterLogic']),
+
+ actions({
+ // Tree manipulation — each takes a path to the target node
+ updateTreeNode: (pathKeys: TreePath, node: FilterNode) => ({ pathKeys, node }),
+ wrapInNot: (pathKeys: TreePath) => ({ pathKeys }),
+ unwrapNot: (pathKeys: TreePath) => ({ pathKeys }),
+ addChild: (pathKeys: TreePath) => ({ pathKeys }),
+ removeChild: (pathKeys: TreePath, childIndex: number) => ({ pathKeys, childIndex }),
+ convertToGroup: (pathKeys: TreePath, groupType: 'and' | 'or') => ({ pathKeys, groupType }),
+ // Test case management
+ addTestCase: true,
+ removeTestCase: (index: number) => ({ index }),
+ updateTestCase: (index: number, updates: Partial<TestCase>) => ({ index, updates }),
+ }),
+
+ forms(({ values }) => ({
+ filterForm: {
+ defaults: DEFAULT_FORM,
+ errors: ({ filter_tree, mode, test_cases }: EventFilterFormValues) => ({
+ // Validation errors go on `mode` (a string field) rather than `filter_tree`
+ // because kea-forms expects errors on object fields to be DeepPartialMap, not strings.
+ mode: (() => {
+ if (mode !== 'disabled' && !treeHasConditions(filter_tree)) {
+ return 'Filter must have at least one condition to be activated'
+ }
+ if (treeHasConditions(filter_tree) && treeHasEmptyValues(filter_tree)) {
+ return 'All conditions must have a value'
+ }
+ if (mode === 'live' && treeHasConditions(filter_tree) && test_cases.length === 0) {
+ return 'Add at least one test case before going live'
+ }
+ return undefined
+ })(),
+ }),
+ submit: async (formValues) => {
+ const { currentTeamId } = values
+
+ // Safety: downgrade to dry_run if tests are failing
+ if (formValues.mode === 'live' && !values.allTestsPass && formValues.test_cases.length > 0) {
+ formValues = { ...formValues, mode: 'dry_run' }
+ }
+
+ // Strip _key from test cases before sending to the API
+ const payload = {
+ ...formValues,
+ test_cases: formValues.test_cases.map(({ _key, ...tc }) => tc),
+ }
+ await api.create(`api/environments/${currentTeamId}/event_filter/`, payload)
+ lemonToast.success('Event filter saved')
+ },
+ },
+ })),
+
+ selectors({
+ currentTeamId: [() => [teamLogic.selectors.currentTeamId], (id: number) => id],
+
+ /** Total number of condition leaves in the current tree. */
+ conditionCount: [
+ (s) => [s.filterForm],
+ (form: EventFilterFormValues): number => countConditions(form.filter_tree),
+ ],
+
+ /** Run each test case against the current tree client-side for live preview. */
+ testResults: [
+ (s) => [s.filterForm],
+ (form: EventFilterFormValues): TestResult[] =>
+ form.test_cases.map((tc) => {
+ const dropped = evaluateFilterTree(form.filter_tree, {
+ event_name: tc.event_name,
+ distinct_id: tc.distinct_id,
+ })
+ const actual = dropped ? 'drop' : 'ingest'
+ return { actual, pass: actual === tc.expected_result }
+ }),
+ ],
+
+ /** True if there are no test cases or all pass. Gates the live mode toggle. */
+ allTestsPass: [
+ (s) => [s.testResults, s.filterForm],
+ (results: TestResult[], form: EventFilterFormValues): boolean =>
+ form.test_cases.length === 0 || results.every((r) => r.pass),
+ ],
+
+ breadcrumbs: [
+ () => [],
+ (): Breadcrumb[] => [
+ {
+ key: 'EventFiltering',
+ name: 'Event ingestion filtering',
+ iconType: 'data_pipeline',
+ },
+ ],
+ ],
+ }),
+
+ // Each listener produces a new immutable tree and updates the form.
+ // All tree mutations go through updateAtPath to preserve structural sharing.
+ listeners(({ actions, values }) => ({
+ updateTreeNode: ({ pathKeys, node }) => {
+ const newTree = updateAtPath(values.filterForm.filter_tree, pathKeys, () => node)
+ actions.setFilterFormValue('filter_tree', newTree)
+ },
+ wrapInNot: ({ pathKeys }) => {
+ const newTree = updateAtPath(values.filterForm.filter_tree, pathKeys, (node) => ({
+ type: 'not' as const,
+ child: node,
+ }))
+ actions.setFilterFormValue('filter_tree', newTree)
+ },
+ unwrapNot: ({ pathKeys }) => {
+ const newTree = updateAtPath(values.filterForm.filter_tree, pathKeys, (node) => {
+ if (node.type === 'not') {
+ return node.child
+ }
+ return node
+ })
+ actions.setFilterFormValue('filter_tree', newTree)
+ },
+ addChild: ({ pathKeys }) => {
+ const newTree = updateAtPath(values.filterForm.filter_tree, pathKeys, (node) => {
+ if (node.type === 'and' || node.type === 'or') {
+ return {
+ ...node,
+ children: [
+ ...node.children,
+ {
+ type: 'condition' as const,
+ field: 'event_name' as const,
+ operator: 'exact' as const,
+ value: '',
+ },
+ ],
+ }
+ }
+ return node
+ })
+ actions.setFilterFormValue('filter_tree', newTree)
+ },
+ removeChild: ({ pathKeys, childIndex }) => {
+ const newTree = updateAtPath(values.filterForm.filter_tree, pathKeys, (node) => {
+ if (node.type === 'and' || node.type === 'or') {
+ return {
+ ...node,
+ children: node.children.filter((_, i) => i !== childIndex),
+ }
+ }
+ return node
+ })
+ actions.setFilterFormValue('filter_tree', newTree)
+ },
+ convertToGroup: ({ pathKeys, groupType }) => {
+ const newTree = updateAtPath(values.filterForm.filter_tree, pathKeys, (node) => ({
+ type: groupType,
+ children: [node],
+ }))
+ actions.setFilterFormValue('filter_tree', newTree)
+ },
+ addTestCase: () => {
+ const newCases = [
+ ...values.filterForm.test_cases,
+ { _key: nextTestCaseKey(), event_name: '', distinct_id: '', expected_result: 'drop' as const },
+ ]
+ actions.setFilterFormValue('test_cases', newCases)
+ },
+ removeTestCase: ({ index }) => {
+ actions.setFilterFormValue(
+ 'test_cases',
+ values.filterForm.test_cases.filter((_, i) => i !== index)
+ )
+ },
+ updateTestCase: ({ index, updates }) => {
+ const newCases = values.filterForm.test_cases.map((tc, i) => (i === index ? { ...tc, ...updates } : tc))
+ actions.setFilterFormValue('test_cases', newCases)
+ },
+ })),
+
+ // Load existing config from the API on mount
+ afterMount(({ actions, values }) => {
+ const { currentTeamId } = values
+ api.get(`api/environments/${currentTeamId}/event_filter/`)
+ .then((data) => {
+ if (!data) {
+ return
+ }
+ actions.setFilterFormValue('id', data.id)
+ actions.setFilterFormValue('mode', data.mode ?? 'disabled')
+ if (data.filter_tree?.type) {
+ actions.setFilterFormValue('filter_tree', data.filter_tree)
+ }
+ const testCases = (data.test_cases ?? []).map((tc: Omit<TestCase, '_key'>) => ({
+ ...tc,
+ _key: nextTestCaseKey(),
+ }))
+ actions.setFilterFormValue('test_cases', testCases)
+ })
+ .catch((error) => {
+ lemonToast.error(`Failed to load event filter config: ${error.message ?? error}`)
+ })
+ }),
+])
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/filterTree.integration.test.ts b/frontend/src/scenes/data-pipelines/event-filtering/filterTree.integration.test.ts
new file mode 100644
index 000000000000..8ad70449b040
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/filterTree.integration.test.ts
@@ -0,0 +1,185 @@
+/**
+ * Integration tests that exercise multiple filter tree modules together,
+ * simulating realistic user workflows: build a tree, manipulate it via
+ * updateAtPath, verify evaluation and expression output.
+ */
+import { evaluateFilterTree, treeHasConditions, treeHasEmptyValues, updateAtPath, FilterNode } from './eventFilterLogic'
+import { filterTreeToExpression } from './filterTreeDisplay'
+import { reorderWithinGroup, moveBetweenGroups } from './filterTreeDnd'
+import { getNodeAtPath, splitParentChild } from './filterTreePath'
+import { NodeIdMap } from './NodeIdMap'
+import { cond, and, or, not } from './testHelpers'
+
+describe('build a tree from scratch and verify evaluation', () => {
+ it('incrementally builds a complex filter and evaluates test cases', () => {
+ // Start with empty root
+ let tree: FilterNode = or()
+ expect(treeHasConditions(tree)).toBe(false)
+
+ // Add first condition: drop $autocapture
+ tree = updateAtPath(tree, [], (node) => {
+ if (node.type === 'or') {
+ return { ...node, children: [...node.children, cond('event_name', 'exact', '$autocapture')] }
+ }
+ return node
+ })
+ expect(treeHasConditions(tree)).toBe(true)
+ expect(evaluateFilterTree(tree, { event_name: '$autocapture' })).toBe(true)
+ expect(evaluateFilterTree(tree, { event_name: '$pageview' })).toBe(false)
+
+ // Add second condition: drop events with bot in distinct_id
+ tree = updateAtPath(tree, [], (node) => {
+ if (node.type === 'or') {
+ return { ...node, children: [...node.children, cond('distinct_id', 'contains', 'bot')] }
+ }
+ return node
+ })
+ expect(evaluateFilterTree(tree, { event_name: '$pageview', distinct_id: 'bot-crawler' })).toBe(true)
+ expect(evaluateFilterTree(tree, { event_name: '$pageview', distinct_id: 'user-1' })).toBe(false)
+
+ // Wrap second condition in NOT — now it means "drop if NOT bot"
+ // Actually let's convert to: drop if $autocapture AND NOT bot (protect bots from being dropped)
+ tree = updateAtPath(tree, [], () =>
+ and(cond('event_name', 'exact', '$autocapture'), not(cond('distinct_id', 'contains', 'bot')))
+ )
+
+ // $autocapture from a bot → ingest (protected by NOT)
+ expect(evaluateFilterTree(tree, { event_name: '$autocapture', distinct_id: 'bot-1' })).toBe(false)
+ // $autocapture from a user → drop
+ expect(evaluateFilterTree(tree, { event_name: '$autocapture', distinct_id: 'user-1' })).toBe(true)
+ // $pageview from a user → ingest (doesn't match $autocapture)
+ expect(evaluateFilterTree(tree, { event_name: '$pageview', distinct_id: 'user-1' })).toBe(false)
+
+ // Verify expression output
+ expect(filterTreeToExpression(tree)).toBe(
+ ['AND', '├── event_name = "$autocapture"', '└── NOT', ' └── distinct_id ~ "bot"'].join('\n')
+ )
+ })
+})
+
+describe('reorder and move operations preserve evaluation', () => {
+ it('reordering within a group does not change evaluation', () => {
+ const tree = or(
+ cond('event_name', 'exact', '$autocapture'),
+ cond('event_name', 'exact', '$drop_me'),
+ cond('distinct_id', 'contains', 'bot')
+ )
+
+ const mockArrayMove = (arr: FilterNode[], from: number, to: number): FilterNode[] => {
+ const result = [...arr]
+ const [item] = result.splice(from, 1)
+ result.splice(to, 0, item)
+ return result
+ }
+
+ const reordered = reorderWithinGroup(tree, [], 0, 2, mockArrayMove)
+ expect(reordered).not.toBeNull()
+
+ // Evaluation should be identical — OR is commutative
+ const testEvents = [
+ { event_name: '$autocapture', distinct_id: 'user-1' },
+ { event_name: '$drop_me', distinct_id: 'user-1' },
+ { event_name: '$pageview', distinct_id: 'bot-1' },
+ { event_name: '$pageview', distinct_id: 'user-1' },
+ ]
+ for (const event of testEvents) {
+ expect(evaluateFilterTree(reordered!, event)).toBe(evaluateFilterTree(tree, event))
+ }
+ })
+
+ it('moving a condition between groups changes evaluation correctly', () => {
+ // OR(AND(condA, condB), AND(condC))
+ const condA = cond('event_name', 'exact', '$autocapture')
+ const condB = cond('distinct_id', 'contains', 'bot')
+ const condC = cond('event_name', 'exact', '$drop_me')
+ const secondAnd = and(condC)
+ const tree = or(and(condA, condB), secondAnd)
+ const nodeIds = new NodeIdMap()
+ nodeIds.buildIndex(tree)
+
+ // Before: drops $autocapture from bots, or $drop_me
+ expect(evaluateFilterTree(tree, { event_name: '$autocapture', distinct_id: 'bot-1' })).toBe(true)
+ expect(evaluateFilterTree(tree, { event_name: '$drop_me', distinct_id: 'user-1' })).toBe(true)
+ expect(evaluateFilterTree(tree, { event_name: '$autocapture', distinct_id: 'user-1' })).toBe(false)
+
+ // Move condB (bot check) from first AND to second AND
+ const result = moveBetweenGroups(tree, [0], 1, nodeIds.nidOf(secondAnd), 1, nodeIds)
+ expect(result).not.toBeNull()
+
+ // After: first AND only has condA (drops all $autocapture)
+ // second AND has condC + condB (drops $drop_me from bots only)
+ expect(evaluateFilterTree(result!, { event_name: '$autocapture', distinct_id: 'user-1' })).toBe(true)
+ expect(evaluateFilterTree(result!, { event_name: '$drop_me', distinct_id: 'user-1' })).toBe(false)
+ expect(evaluateFilterTree(result!, { event_name: '$drop_me', distinct_id: 'bot-1' })).toBe(true)
+ })
+})
+
+describe('NodeIdMap + path navigation round-trip', () => {
+ it('every node in a complex tree is reachable via its indexed path', () => {
+ const tree = or(
+ and(cond('event_name', 'exact', 'a'), not(cond('distinct_id', 'exact', 'b'))),
+ cond('event_name', 'exact', 'c')
+ )
+ const nodeIds = new NodeIdMap()
+ nodeIds.buildIndex(tree)
+
+ // Collect all nodes by walking the tree
+ function collectNodes(node: FilterNode): FilterNode[] {
+ const nodes = [node]
+ if (node.type === 'and' || node.type === 'or') {
+ for (const child of node.children) {
+ nodes.push(...collectNodes(child))
+ }
+ } else if (node.type === 'not') {
+ nodes.push(...collectNodes(node.child))
+ }
+ return nodes
+ }
+
+ const allNodes = collectNodes(tree)
+ expect(allNodes.length).toBe(6) // or, and, cond-a, not, cond-b, cond-c
+
+ for (const node of allNodes) {
+ const nid = nodeIds.nidOf(node)
+ const path = nodeIds.pathOf(nid)
+ expect(path).not.toBeUndefined()
+ expect(getNodeAtPath(tree, path!)).toBe(node)
+ }
+ })
+
+ it('splitParentChild correctly identifies parent for every non-root node', () => {
+ const tree = or(
+ and(cond('event_name', 'exact', 'a'), cond('event_name', 'exact', 'b')),
+ cond('event_name', 'exact', 'c')
+ )
+ const nodeIds = new NodeIdMap()
+ nodeIds.buildIndex(tree)
+
+ // Check condA's parent is the inner AND
+ const condAPath = nodeIds.pathOf(nodeIds.nidOf(tree.children[0]))!
+ // condA is at [0], its parent split should be {parentPath: [], childIndex: 0}
+ const condAParent = splitParentChild(condAPath)
+ expect(condAParent).not.toBeNull()
+ expect(getNodeAtPath(tree, condAParent!.parentPath)).toBe(tree)
+ })
+})
+
+describe('validation + evaluation consistency', () => {
+ it('a tree with empty values fails validation but still evaluates safely', () => {
+ const tree = and(cond('event_name', 'exact', ''), cond('distinct_id', 'exact', 'user'))
+
+ expect(treeHasEmptyValues(tree)).toBe(true)
+ expect(treeHasConditions(tree)).toBe(true)
+
+ // Empty condition value: event_name === '' — only matches empty string event names
+ expect(evaluateFilterTree(tree, { event_name: '', distinct_id: 'user' })).toBe(true)
+ // Normal events don't match the empty condition
+ expect(evaluateFilterTree(tree, { event_name: '$pageview', distinct_id: 'user' })).toBe(false)
+ })
+
+ it('disabled filter (empty tree) never drops anything', () => {
+ const tree = or()
+ expect(treeHasConditions(tree)).toBe(false)
+ expect(evaluateFilterTree(tree, { event_name: '$anything', distinct_id: 'anyone' })).toBe(false)
+ })
+})
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDisplay.test.ts b/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDisplay.test.ts
new file mode 100644
index 000000000000..064a0da0c2a7
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDisplay.test.ts
@@ -0,0 +1,101 @@
+import { isTreeEmpty, filterTreeToExpression, nodeSummary } from './filterTreeDisplay'
+import { cond, and, or, not } from './testHelpers'
+
+describe('isTreeEmpty', () => {
+ it.each([
+ ['condition is not empty', cond(), false],
+ ['empty or', or(), true],
+ ['empty and', and(), true],
+ ['not wrapping empty group', not(or()), true],
+ ['not wrapping condition', not(cond()), false],
+ ['group with condition', or(cond()), false],
+ ['nested empty groups recurse', or(and()), true],
+ ['nested empty groups mixed with condition', or(and(), cond()), false],
+ ])('%s', (_name, tree, expected) => {
+ expect(isTreeEmpty(tree)).toBe(expected)
+ })
+})
+
+describe('filterTreeToExpression', () => {
+ it('renders a simple condition', () => {
+ expect(filterTreeToExpression(cond('event_name', 'exact', '$pageview'))).toBe('event_name = "$pageview"')
+ })
+
+ it('renders contains as ~', () => {
+ expect(filterTreeToExpression(cond('distinct_id', 'contains', 'bot'))).toBe('distinct_id ~ "bot"')
+ })
+
+ it('renders AND group with tree connectors', () => {
+ const tree = and(cond('event_name', 'exact', 'a'), cond('distinct_id', 'exact', 'u1'))
+ expect(filterTreeToExpression(tree)).toBe(['AND', '├── event_name = "a"', '└── distinct_id = "u1"'].join('\n'))
+ })
+
+ it('renders OR group with tree connectors', () => {
+ const tree = or(cond('event_name', 'exact', 'a'), cond('event_name', 'exact', 'b'))
+ expect(filterTreeToExpression(tree)).toBe(['OR', '├── event_name = "a"', '└── event_name = "b"'].join('\n'))
+ })
+
+ it('renders NOT with child', () => {
+ expect(filterTreeToExpression(not(cond('event_name', 'exact', 'x')))).toBe(
+ ['NOT', '└── event_name = "x"'].join('\n')
+ )
+ })
+
+ it('renders empty group', () => {
+ expect(filterTreeToExpression(or())).toBe('OR (empty)')
+ })
+
+ it('renders nested AND inside OR', () => {
+ const tree = or(
+ cond('event_name', 'exact', 'a'),
+ and(cond('event_name', 'exact', 'b'), cond('distinct_id', 'contains', 'bot'))
+ )
+ expect(filterTreeToExpression(tree)).toBe(
+ ['OR', '├── event_name = "a"', '└── AND', ' ├── event_name = "b"', ' └── distinct_id ~ "bot"'].join(
+ '\n'
+ )
+ )
+ })
+
+ it('renders NOT wrapping a group', () => {
+ const tree = not(and(cond('event_name', 'exact', 'a'), cond('event_name', 'exact', 'b')))
+ expect(filterTreeToExpression(tree)).toBe(
+ ['NOT', '└── AND', ' ├── event_name = "a"', ' └── event_name = "b"'].join('\n')
+ )
+ })
+
+ it('renders deeply nested tree', () => {
+ const tree = or(
+ cond('event_name', 'exact', '$drop_me'),
+ and(cond('event_name', 'exact', '$internal'), not(cond('distinct_id', 'contains', 'admin')))
+ )
+ expect(filterTreeToExpression(tree)).toBe(
+ [
+ 'OR',
+ '├── event_name = "$drop_me"',
+ '└── AND',
+ ' ├── event_name = "$internal"',
+ ' └── NOT',
+ ' └── distinct_id ~ "admin"',
+ ].join('\n')
+ )
+ })
+})
+
+describe('nodeSummary', () => {
+ it('summarizes a condition', () => {
+ expect(nodeSummary(cond('event_name', 'exact', '$pageview'))).toBe('event_name exact "$pageview"')
+ })
+
+ it('summarizes a NOT node', () => {
+ expect(nodeSummary(not(cond()))).toBe('NOT (...)')
+ })
+
+ it('summarizes an AND group with count', () => {
+ expect(nodeSummary(and(cond(), cond(), cond()))).toBe('AND group (3 items)')
+ })
+
+ it('summarizes an empty OR group', () => {
+ expect(nodeSummary(or())).toBe('OR group (0 items)')
+ })
+})
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDisplay.ts b/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDisplay.ts
new file mode 100644
index 000000000000..ff759741396d
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDisplay.ts
@@ -0,0 +1,75 @@
+/** Display helpers for the filter expression tree. */
+import type { FilterNode } from './eventFilterLogic'
+
+/** True if the tree has no condition leaves (only empty groups or NOT wrappers). */
+export function isTreeEmpty(node: FilterNode): boolean {
+ if (!node?.type) {
+ return true
+ }
+ if (node.type === 'condition') {
+ return false
+ }
+ if (node.type === 'not') {
+ return isTreeEmpty(node.child)
+ }
+ return node.children.length === 0 || node.children.every(isTreeEmpty)
+}
+
+/**
+ * Render the filter tree as a human-readable tree diagram.
+ * Used in the "Show expression" modal. Example output:
+ *
+ * OR
+ * ├── event_name = "$drop_me"
+ * └── AND
+ * ├── event_name = "$internal"
+ * └── distinct_id ~ "bot-"
+ *
+ * `indent` is the whitespace prefix for continuation lines (children).
+ * The node's own label is rendered without indent — the caller prepends
+ * the connector (├── or └──) and indent.
+ */
+function renderNode(node: FilterNode, indent: string): string {
+ switch (node.type) {
+ case 'condition': {
+ const op = node.operator === 'exact' ? '=' : '~'
+ return `${node.field} ${op} "${node.value}"`
+ }
+ case 'not': {
+ const childLine = renderNode(node.child, indent + ' ')
+ return `NOT\n${indent}└── ${childLine}`
+ }
+ case 'and':
+ case 'or': {
+ if (node.children.length === 0) {
+ return `${node.type.toUpperCase()} (empty)`
+ }
+ const lines = node.children.map((child, i) => {
+ const isLast = i === node.children.length - 1
+ const connector = isLast ? '└── ' : '├── '
+ const childIndent = indent + (isLast ? ' ' : '│ ')
+ return `${indent}${connector}${renderNode(child, childIndent)}`
+ })
+ return `${node.type.toUpperCase()}\n${lines.join('\n')}`
+ }
+ }
+}
+
+/**
+ * Render the filter tree as a human-readable tree diagram.
+ * Used in the "Show expression" modal.
+ */
+export function filterTreeToExpression(node: FilterNode): string {
+ return renderNode(node, '')
+}
+
+/** One-line summary of a node, shown in the DnD drag overlay. */
+export function nodeSummary(node: FilterNode): string {
+ if (node.type === 'condition') {
+ return `${node.field} ${node.operator} "${node.value}"`
+ }
+ if (node.type === 'not') {
+ return 'NOT (...)'
+ }
+ return `${node.type.toUpperCase()} group (${node.children.length} items)`
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDnd.test.ts b/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDnd.test.ts
new file mode 100644
index 000000000000..6508664c6b0f
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDnd.test.ts
@@ -0,0 +1,187 @@
+import { FilterNode, FilterAndNode, FilterOrNode } from './eventFilterLogic'
+import { resolveDropTarget, reorderWithinGroup, moveBetweenGroups } from './filterTreeDnd'
+import { NodeIdMap } from './NodeIdMap'
+import { cond, and, or, not } from './testHelpers'
+
+function indexed(tree: FilterNode): NodeIdMap {
+ const nodeIds = new NodeIdMap()
+ nodeIds.buildIndex(tree)
+ return nodeIds
+}
+
+describe('resolveDropTarget', () => {
+ const condA = cond('event_name', 'exact', 'a')
+ const condB = cond('event_name', 'exact', 'b')
+ const condC = cond('event_name', 'exact', 'c')
+ const tree = or(condA, and(condB, condC))
+ const nodeIds = indexed(tree)
+ const innerAnd = tree.children[1]
+
+ it('resolves drop on a group droppable → append at end', () => {
+ const result = resolveDropTarget(`drop:${nodeIds.nidOf(innerAnd)}`, tree, nodeIds)
+ expect(result).toEqual({ groupPath: [1], insertIndex: 2 })
+ })
+
+ it('resolves drop on root group droppable', () => {
+ const result = resolveDropTarget(`drop:${nodeIds.nidOf(tree)}`, tree, nodeIds)
+ expect(result).toEqual({ groupPath: [], insertIndex: 2 })
+ })
+
+ it('resolves drop on a sortable item → insert at its position', () => {
+ const result = resolveDropTarget(nodeIds.nidOf(condB), tree, nodeIds)
+ expect(result).toEqual({ groupPath: [1], insertIndex: 0 })
+ })
+
+ it('returns null for unknown nid', () => {
+ expect(resolveDropTarget('unknown', tree, nodeIds)).toBeNull()
+ expect(resolveDropTarget('drop:unknown', tree, nodeIds)).toBeNull()
+ })
+
+ it('returns null if drop target is a condition (not a group)', () => {
+ expect(resolveDropTarget(`drop:${nodeIds.nidOf(condA)}`, tree, nodeIds)).toBeNull()
+ })
+})
+
+describe('reorderWithinGroup', () => {
+ const mockArrayMove = (arr: FilterNode[], from: number, to: number): FilterNode[] => {
+ const result = [...arr]
+ const [item] = result.splice(from, 1)
+ result.splice(to, 0, item)
+ return result
+ }
+
+ it('reorders children in root group', () => {
+ const a = cond('event_name', 'exact', 'a')
+ const b = cond('event_name', 'exact', 'b')
+ const c = cond('event_name', 'exact', 'c')
+ const tree = or(a, b, c)
+
+ const result = reorderWithinGroup(tree, [], 0, 2, mockArrayMove)
+ expect(result).toEqual(or(b, c, a))
+ })
+
+ it('reorders children in a nested group', () => {
+ const a = cond('event_name', 'exact', 'a')
+ const b = cond('event_name', 'exact', 'b')
+ const tree = or(and(a, b))
+
+ const result = reorderWithinGroup(tree, [0], 0, 1, mockArrayMove)
+ expect(result).toEqual(and(b, a))
+ })
+
+ it('returns null if path points to a condition', () => {
+ const tree = or(cond())
+ expect(reorderWithinGroup(tree, [0], 0, 1, mockArrayMove)).toBeNull()
+ })
+
+ it('returns null if path points to a NOT node', () => {
+ const tree = or(not(cond()))
+ expect(reorderWithinGroup(tree, [0], 0, 1, mockArrayMove)).toBeNull()
+ })
+
+ it('no-op reorder (same index) returns identical structure', () => {
+ const a = cond('event_name', 'exact', 'a')
+ const b = cond('event_name', 'exact', 'b')
+ const tree = or(a, b)
+ const result = reorderWithinGroup(tree, [], 0, 0, mockArrayMove)
+ expect(result).toEqual(or(a, b))
+ })
+})
+
+describe('moveBetweenGroups', () => {
+ it('moves a node from one group to another', () => {
+ const a = cond('event_name', 'exact', 'a')
+ const b = cond('event_name', 'exact', 'b')
+ const c = cond('event_name', 'exact', 'c')
+ const secondAnd = and(c)
+ const tree = or(and(a, b), secondAnd)
+ const nodeIds = indexed(tree)
+
+ const result = moveBetweenGroups(tree, [0], 0, nodeIds.nidOf(secondAnd), 1, nodeIds)
+
+ expect(result).not.toBeNull()
+ const resultOr = result as FilterOrNode
+ const firstAnd = resultOr.children[0] as FilterAndNode
+ const secondAndResult = resultOr.children[1] as FilterAndNode
+ expect(firstAnd.children).toHaveLength(1)
+ expect(firstAnd.children[0]).toMatchObject({ value: 'b' })
+ expect(secondAndResult.children).toHaveLength(2)
+ expect(secondAndResult.children[0]).toMatchObject({ value: 'c' })
+ expect(secondAndResult.children[1]).toMatchObject({ value: 'a' })
+ })
+
+ it('returns null if source is not a group', () => {
+ const tree = not(cond())
+ const nodeIds = indexed(tree)
+ expect(moveBetweenGroups(tree, [], 0, 'anything', 0, nodeIds)).toBeNull()
+ })
+
+ it('does not mutate the original tree', () => {
+ const a = cond('event_name', 'exact', 'a')
+ const b = cond('event_name', 'exact', 'b')
+ const c = cond('event_name', 'exact', 'c')
+ const secondAnd = and(c)
+ const tree = or(and(a, b), secondAnd)
+ const nodeIds = indexed(tree)
+ const original = JSON.parse(JSON.stringify(tree))
+
+ moveBetweenGroups(tree, [0], 0, nodeIds.nidOf(secondAnd), 1, nodeIds)
+
+ expect(tree).toEqual(original)
+ })
+
+ it('moves last child out of a group (leaves it empty)', () => {
+ const a = cond('event_name', 'exact', 'a')
+ const b = cond('event_name', 'exact', 'b')
+ const secondAnd = and(b)
+ const tree = or(and(a), secondAnd)
+ const nodeIds = indexed(tree)
+
+ const result = moveBetweenGroups(tree, [0], 0, nodeIds.nidOf(secondAnd), 1, nodeIds)
+
+ expect(result).not.toBeNull()
+ const resultOr = result as FilterOrNode
+ expect((resultOr.children[0] as FilterAndNode).children).toHaveLength(0)
+ expect((resultOr.children[1] as FilterAndNode).children).toHaveLength(2)
+ })
+
+ it('moves a node to root group', () => {
+ const a = cond('event_name', 'exact', 'a')
+ const b = cond('event_name', 'exact', 'b')
+ const tree = or(and(a, b))
+ const nodeIds = indexed(tree)
+
+ // Move condA from the inner AND to the root OR at index 1
+ const result = moveBetweenGroups(tree, [0], 0, nodeIds.nidOf(tree), 1, nodeIds)
+
+ expect(result).not.toBeNull()
+ const resultOr = result as FilterOrNode
+ expect(resultOr.children).toHaveLength(2)
+ expect((resultOr.children[0] as FilterAndNode).children).toHaveLength(1)
+ expect(resultOr.children[1]).toMatchObject({ value: 'a' })
+ })
+
+ it('handles index shift when source and dest share a parent', () => {
+ // OR(condA, AND(condB, condC))
+ // Drag condA (index 0 in root OR) into the AND group (index 1 in root OR)
+ // After removing condA, the AND group shifts from index 1 to index 0
+ // Using nid-based resolution avoids the off-by-one
+ const condA = cond('event_name', 'exact', 'a')
+ const condB = cond('event_name', 'exact', 'b')
+ const condC = cond('event_name', 'exact', 'c')
+ const innerAnd = and(condB, condC)
+ const tree = or(condA, innerAnd)
+ const nodeIds = indexed(tree)
+
+ const result = moveBetweenGroups(tree, [], 0, nodeIds.nidOf(innerAnd), 2, nodeIds)
+
+ expect(result).not.toBeNull()
+ const resultOr = result as FilterOrNode
+ expect(resultOr.children).toHaveLength(1)
+ const andGroup = resultOr.children[0] as FilterAndNode
+ expect(andGroup.children).toHaveLength(3)
+ expect(andGroup.children[0]).toMatchObject({ value: 'b' })
+ expect(andGroup.children[1]).toMatchObject({ value: 'c' })
+ expect(andGroup.children[2]).toMatchObject({ value: 'a' })
+ })
+})
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDnd.ts b/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDnd.ts
new file mode 100644
index 000000000000..942c7714623a
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/filterTreeDnd.ts
@@ -0,0 +1,157 @@
+/**
+ * DnD tree operations for the filter expression tree.
+ *
+ * Drag and drop lets users reorder conditions within a group or move them
+ * between groups. The scene's handleDragEnd callback orchestrates this:
+ *
+ * 1. Look up the dragged node's path via its stable nid
+ * 2. resolveDropTarget — figure out which group the node was dropped on
+ * and at what index (end of group if dropped on the group droppable,
+ * or at a sibling's position if dropped on a sortable item)
+ * 3. Guard: bail if dropping into own descendant (would create a cycle)
+ * 4. If same group → reorderWithinGroup (arrayMove within children)
+ * If different group → moveBetweenGroups (clone tree, splice out, splice in)
+ *
+ * All functions are pure: they take a tree and return a new tree.
+ */
+import { updateAtPath } from './eventFilterLogic'
+import type { FilterNode, TreePath } from './eventFilterLogic'
+import { getNodeAtPath, splitParentChild } from './filterTreePath'
+import { NodeIdMap } from './NodeIdMap'
+
+interface DropTarget {
+ groupPath: TreePath
+ insertIndex: number
+}
+
+/**
+ * Determine where a dragged node should land.
+ *
+ * Drop target IDs come in two forms:
+ * - "drop:<nid>" — the droppable zone of a group → append at end
+ * - "<nid>" — a sortable sibling item → insert at that item's position
+ *
+ * Returns the target group's path and the insert index, or null if the
+ * drop target can't be resolved (e.g. nid not found, target isn't a group).
+ */
+export function resolveDropTarget(overIdStr: string, tree: FilterNode, nodeIds: NodeIdMap): DropTarget | null {
+ if (overIdStr.startsWith('drop:')) {
+ // Dropped on a group droppable — append at end
+ const groupNid = overIdStr.slice(5)
+ const groupPath = nodeIds.pathOf(groupNid)
+ if (!groupPath) {
+ return null
+ }
+ const targetNode = groupPath.length === 0 ? tree : getNodeAtPath(tree, groupPath)
+ if (!targetNode || (targetNode.type !== 'and' && targetNode.type !== 'or')) {
+ return null
+ }
+ return { groupPath, insertIndex: targetNode.children.length }
+ }
+ // Dropped on a sortable item — insert at its position
+ const overPath = nodeIds.pathOf(overIdStr)
+ if (!overPath) {
+ return null
+ }
+ const overParent = splitParentChild(overPath)
+ if (!overParent) {
+ return null
+ }
+ return { groupPath: overParent.parentPath, insertIndex: overParent.childIndex }
+}
+
+/**
+ * Reorder a child within the same AND/OR group.
+ *
+ * Returns the updated group node with children reordered (caller uses
+ * updateTreeNode to patch it into the tree). Returns null if the path
+ * doesn't point to an AND/OR group.
+ *
+ * Takes arrayMove as a parameter to avoid coupling to @dnd-kit/sortable.
+ */
+export function reorderWithinGroup(
+ tree: FilterNode,
+ groupPath: TreePath,
+ fromIndex: number,
+ toIndex: number,
+ arrayMoveFn: (arr: FilterNode[], from: number, to: number) => FilterNode[]
+): FilterNode | null {
+ const parentNode = groupPath.length === 0 ? tree : getNodeAtPath(tree, groupPath)
+ if (!parentNode || (parentNode.type !== 'and' && parentNode.type !== 'or')) {
+ return null
+ }
+ const newChildren = arrayMoveFn([...parentNode.children], fromIndex, toIndex)
+ return { ...parentNode, children: newChildren } as FilterNode
+}
+
+/**
+ * After removing sourcePath[sourceIndex], any dest path that passes through
+ * the same parent at a later index needs that index decremented.
+ * E.g. removing []:0 shifts dest [1,'child'] to [0,'child'].
+ */
+function adjustDestPath(sourcePath: TreePath, sourceIndex: number, destPath: TreePath): TreePath {
+ if (destPath.length <= sourcePath.length) {
+ return destPath
+ }
+ for (let i = 0; i < sourcePath.length; i++) {
+ if (destPath[i] !== sourcePath[i]) {
+ return destPath
+ }
+ }
+ const siblingStep = destPath[sourcePath.length]
+ if (typeof siblingStep === 'number' && siblingStep > sourceIndex) {
+ const adjusted = [...destPath]
+ adjusted[sourcePath.length] = siblingStep - 1
+ return adjusted
+ }
+ return destPath
+}
+
+/**
+ * Move a node from one AND/OR group to another.
+ *
+ * Resolves the destination group by nid on the original tree, then applies
+ * the remove and insert as two immutable updateAtPath calls with path
+ * adjustment to account for index shifts from the removal.
+ */
+export function moveBetweenGroups(
+ tree: FilterNode,
+ sourcePath: TreePath,
+ sourceIndex: number,
+ destGroupNid: string,
+ destIndex: number,
+ nodeIds: NodeIdMap
+): FilterNode | null {
+ const srcParent = sourcePath.length === 0 ? tree : getNodeAtPath(tree, sourcePath)
+ if (!srcParent || (srcParent.type !== 'and' && srcParent.type !== 'or')) {
+ return null
+ }
+ const movedNode = srcParent.children[sourceIndex]
+
+ // Resolve dest path on the original tree before any mutations
+ const originalDestPath = nodeIds.pathOf(destGroupNid)
+ if (originalDestPath === undefined) {
+ return null
+ }
+
+ // Step 1: remove from source
+ const afterRemove = updateAtPath(tree, sourcePath, (node) => {
+ if (node.type !== 'and' && node.type !== 'or') {
+ return node
+ }
+ return { ...node, children: node.children.filter((_, i) => i !== sourceIndex) }
+ })
+
+ // Step 2: adjust dest path for index shift caused by the removal
+ const destPath = adjustDestPath(sourcePath, sourceIndex, originalDestPath)
+
+ // Step 3: insert into destination
+ return updateAtPath(afterRemove, destPath, (node) => {
+ if (node.type !== 'and' && node.type !== 'or') {
+ return node
+ }
+ const newChildren = [...node.children]
+ newChildren.splice(destIndex, 0, movedNode)
+ return { ...node, children: newChildren }
+ })
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/filterTreePath.test.ts b/frontend/src/scenes/data-pipelines/event-filtering/filterTreePath.test.ts
new file mode 100644
index 000000000000..7b0c387e97d6
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/filterTreePath.test.ts
@@ -0,0 +1,80 @@
+import { getNodeAtPath, splitParentChild, isAncestorPath } from './filterTreePath'
+import { cond, and, or, not } from './testHelpers'
+
+describe('getNodeAtPath', () => {
+ const condA = cond('event_name', 'exact', 'a')
+ const condB = cond('event_name', 'exact', 'b')
+ const condC = cond('distinct_id', 'exact', 'c')
+ const tree = and(or(condA, condB), not(condC))
+
+ it('returns root for empty path', () => {
+ expect(getNodeAtPath(tree, [])).toBe(tree)
+ })
+
+ it('navigates into children by index', () => {
+ expect(getNodeAtPath(tree, [0])).toBe(tree.children[0])
+ expect(getNodeAtPath(tree, [0, 0])).toBe(condA)
+ expect(getNodeAtPath(tree, [0, 1])).toBe(condB)
+ })
+
+ it('navigates through NOT with "child"', () => {
+ expect(getNodeAtPath(tree, [1, 'child'])).toBe(condC)
+ })
+
+ it('returns undefined for out-of-bounds index', () => {
+ expect(getNodeAtPath(tree, [5])).toBeUndefined()
+ })
+
+ it('returns undefined for invalid step type', () => {
+ expect(getNodeAtPath(tree, [0, 0, 0])).toBeUndefined()
+ expect(getNodeAtPath(tree, ['child'])).toBeUndefined()
+ })
+})
+
+describe('splitParentChild', () => {
+ it('returns null for empty path (root)', () => {
+ expect(splitParentChild([])).toBeNull()
+ })
+
+ it('splits a single-step path', () => {
+ expect(splitParentChild([1])).toEqual({ parentPath: [], childIndex: 1 })
+ })
+
+ it('splits a multi-step path', () => {
+ expect(splitParentChild([0, 2])).toEqual({ parentPath: [0], childIndex: 2 })
+ })
+
+ it('returns null if last step is "child" (NOT node)', () => {
+ expect(splitParentChild([1, 'child'])).toBeNull()
+ })
+
+ it('handles path through NOT then into group child', () => {
+ expect(splitParentChild([1, 'child', 0])).toEqual({ parentPath: [1, 'child'], childIndex: 0 })
+ })
+})
+
+describe('isAncestorPath', () => {
+ it('empty path is ancestor of any non-empty path', () => {
+ expect(isAncestorPath([], [0])).toBe(true)
+ expect(isAncestorPath([], [0, 1])).toBe(true)
+ })
+
+ it('path is not its own ancestor', () => {
+ expect(isAncestorPath([0], [0])).toBe(false)
+ expect(isAncestorPath([], [])).toBe(false)
+ })
+
+ it('prefix match is ancestor', () => {
+ expect(isAncestorPath([0], [0, 1])).toBe(true)
+ expect(isAncestorPath([0, 1], [0, 1, 'child'])).toBe(true)
+ })
+
+ it('different prefix is not ancestor', () => {
+ expect(isAncestorPath([0], [1, 0])).toBe(false)
+ expect(isAncestorPath([0, 1], [0, 2])).toBe(false)
+ })
+
+ it('longer path is not ancestor of shorter', () => {
+ expect(isAncestorPath([0, 1], [0])).toBe(false)
+ })
+})
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/filterTreePath.ts b/frontend/src/scenes/data-pipelines/event-filtering/filterTreePath.ts
new file mode 100644
index 000000000000..720543e10bfe
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/filterTreePath.ts
@@ -0,0 +1,44 @@
+/** Path navigation utilities for the filter expression tree. */
+import type { FilterNode, TreePath } from './eventFilterLogic'
+
+/** Walk a TreePath from root and return the node at the end, or undefined if the path is invalid. */
+export function getNodeAtPath(tree: FilterNode, path: TreePath): FilterNode | undefined {
+ let current: FilterNode | undefined = tree
+ for (const step of path) {
+ if (!current) {
+ return undefined
+ }
+ if (typeof step === 'number' && (current.type === 'and' || current.type === 'or')) {
+ current = current.children[step]
+ } else if (step === 'child' && current.type === 'not') {
+ current = current.child
+ } else {
+ return undefined
+ }
+ }
+ return current
+}
+
+/**
+ * Split a path into the parent group's path and the child's index within it.
+ * Returns null for root paths or paths ending with 'child' (NOT nodes don't
+ * have a numeric index). Used to find which group a dragged node belongs to.
+ */
+export function splitParentChild(path: TreePath): { parentPath: TreePath; childIndex: number } | null {
+ if (path.length === 0) {
+ return null
+ }
+ const last = path[path.length - 1]
+ if (typeof last !== 'number') {
+ return null
+ }
+ return { parentPath: path.slice(0, -1), childIndex: last }
+}
+
+/** True if path `a` is a strict prefix of path `b` (a is an ancestor of b). */
+export function isAncestorPath(a: TreePath, b: TreePath): boolean {
+ if (a.length >= b.length) {
+ return false
+ }
+ return a.every((seg, i) => seg === b[i])
+}
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/testHelpers.ts b/frontend/src/scenes/data-pipelines/event-filtering/testHelpers.ts
new file mode 100644
index 000000000000..ff422970d271
--- /dev/null
+++ b/frontend/src/scenes/data-pipelines/event-filtering/testHelpers.ts
@@ -0,0 +1,21 @@
+import { FilterNode, FilterConditionNode, FilterAndNode, FilterOrNode, FilterNotNode } from './eventFilterLogic'
+
+export function cond(
+ field: 'event_name' | 'distinct_id' = 'event_name',
+ operator: 'exact' | 'contains' = 'exact',
+ value: string = 'pageview'
+): FilterConditionNode {
+ return { type: 'condition', field, operator, value }
+}
+
+export function and(...children: FilterNode[]): FilterAndNode {
+ return { type: 'and', children }
+}
+
+export function or(...children: FilterNode[]): FilterOrNode {
+ return { type: 'or', children }
+}
+
+export function not(child: FilterNode): FilterNotNode {
+ return { type: 'not', child }
+}
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index f8ae2648be3b..f943462c5fa2 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -165,6 +165,7 @@ export enum Scene {
Tracing = 'Tracing',
Metrics = 'Metrics',
Transformations = 'Transformations',
+ EventFiltering = 'EventFiltering',
Unsubscribe = 'Unsubscribe',
UserInterview = 'UserInterview',
UserInterviewResponse = 'UserInterviewResponse',
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index a0a5dedf5762..a91815d6a229 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -566,6 +566,12 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {
activityScope: ActivityScope.HOG_FUNCTION,
iconType: 'data_pipeline',
},
+ [Scene.EventFiltering]: {
+ projectBased: true,
+ name: 'Event ingestion filtering',
+ description: 'Drop events at ingestion time based on event metadata.',
+ iconType: 'data_pipeline',
+ },
[Scene.Unsubscribe]: { allowUnauthenticated: true, layout: 'app-raw' },
[Scene.VerifyEmail]: { allowUnauthenticated: true, layout: 'plain' },
[Scene.WebAnalyticsPageReports]: {
@@ -860,6 +866,7 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.materializedColumns()]: [Scene.MaterializedColumns, 'materializedColumns'],
[urls.models()]: [Scene.Models, 'models'],
[urls.transformations()]: [Scene.Transformations, 'transformations'],
+ [urls.eventFiltering()]: [Scene.EventFiltering, 'eventFiltering'],
[urls.toolbarLaunch()]: [Scene.ToolbarLaunch, 'toolbarLaunch'],
[urls.site(':url')]: [Scene.Site, 'site'],
[urls.login()]: [Scene.Login, 'login'],
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 8175208643a1..ec276fbd652b 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -46,6 +46,7 @@ export const urls = {
destinations: (): string => '/data-management/destinations',
models: (tab?: ModelsSceneTab): string => `/models${tab ? `/${tab}` : ''}`,
transformations: (): string => '/data-management/transformations',
+ eventFiltering: (): string => '/data-management/event-filtering',
activity: (tab: ActivityTab | ':tab' = ActivityTab.ExploreEvents): string => `/activity/${tab}`,
event: (id: string, timestamp: string): string =>
`/events/${encodeURIComponent(id)}/${encodeURIComponent(timestamp)}`,
diff --git a/posthog/api/event_filter_config.py b/posthog/api/event_filter_config.py
index da6bc08e5d98..7dcece6565b3 100644
--- a/posthog/api/event_filter_config.py
+++ b/posthog/api/event_filter_config.py
@@ -18,6 +18,7 @@ from posthog.api.app_metrics2 import (
fetch_app_metrics_trends,
)
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.models.event_filter_config import (
EventFilterConfig,
run_test_cases,
@@ -143,6 +144,7 @@ class EventFilterConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(responses={200: AppMetricResponseSerializer})
@action(detail=False, methods=["GET"], url_path="metrics")
def metrics(self, request: Request, **kwargs):
+ tag_queries(product=Product.INGESTION, feature=Feature.EVENT_FILTERS)
params = self._parse_metrics_params(request)
if params is None:
return Response(AppMetricResponseSerializer(instance=AppMetricsResponse(labels=[], series=[])).data)
@@ -152,6 +154,7 @@ class EventFilterConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(responses={200: AppMetricsTotalsResponseSerializer})
@action(detail=False, methods=["GET"], url_path="metrics/totals")
def metrics_totals(self, request: Request, **kwargs):
+ tag_queries(product=Product.INGESTION, feature=Feature.EVENT_FILTERS)
params = self._parse_metrics_params(request)
if params is None:
return Response(AppMetricsTotalsResponseSerializer(instance=AppMetricsTotalsResponse(totals={})).data)
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index ab8cef89a57c..f66282d2441c 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -39,6 +39,7 @@ class Product(StrEnum):
EXPERIMENTS = "experiments"
FEATURE_FLAGS = "feature_flags"
GROUP_ANALYTICS = "group_analytics"
+ INGESTION = "ingestion"
LLM_ANALYTICS = "llm_analytics"
LOGS = "logs"
MARKETING_ANALYTICS = "marketing_analytics"
@@ -82,6 +83,7 @@ class Feature(StrEnum):
PREAGGREGATION = "preaggregation"
DATA_DELETION = "data_deletion"
ENRICHMENT = "enrichment" # background tasks that derive/sync data (not customer-facing)
+ EVENT_FILTERS = "event_filters"
SCHEMA_INTROSPECTION = "schema_introspection"
# Specific scenes that fan out into multiple ad-hoc queries; tagged separately so query
# usage analysis can attribute load to the originating product surface.
diff --git a/products/cdp/manifest.tsx b/products/cdp/manifest.tsx
index e7f95d707b5b..e6100b4626fe 100644
--- a/products/cdp/manifest.tsx
+++ b/products/cdp/manifest.tsx
@@ -15,12 +15,21 @@ export const manifest: ProductManifest = {
activityScope: 'HogFunction',
iconType: 'data_pipeline',
},
+ EventFiltering: {
+ import: () => import('../../frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene'),
+ projectBased: true,
+ name: 'Event ingestion filtering',
+ description: 'Drop events at ingestion time based on event metadata.',
+ iconType: 'data_pipeline',
+ },
},
routes: {
'/transformations': ['Transformations', 'transformations'],
+ '/event-filtering': ['EventFiltering', 'eventFiltering'],
},
urls: {
transformations: (): string => '/transformations',
+ eventFiltering: (): string => '/event-filtering',
},
treeItemsNew: [
{
@@ -75,6 +84,15 @@ export const manifest: ProductManifest = {
sceneKey: 'Transformations',
sceneKeys: ['Transformations'],
},
+ {
+ path: 'Event ingestion filtering',
+ category: 'Pipeline',
+ type: 'event_filter',
+ iconType: 'data_pipeline_metadata',
+ href: urls.eventFiltering(),
+ sceneKey: 'EventFiltering',
+ sceneKeys: ['EventFiltering'],
+ },
{
path: `Destinations`,
category: 'Pipeline',