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: Add more filter operations to Web analytics live overview (#64712)

Jordan Mryyanac0686e28ac0
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index c0d3bd4c887b..70b643acf4db 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -334,6 +334,7 @@ export const FEATURE_FLAGS = {
LEGAL_DOCUMENTS: 'legal-documents', // owner: @rafaeelaudibert #team-growth
LINKS: 'links', // owner: @marconlp #team-link (team doesn't exist for now, maybe will come back in the future)
LIVE_DEBUGGER: 'live-debugger', // owner: @marcecoll
+ LIVE_EVENTS_RICH_FILTERS: 'live-events-rich-filters', // owner: @jordanm-posthog #team-web-analytics
LIVESTREAM_TUI: 'livestream-tui', // owner: @rafaeelaudibert #team-growth
LLM_ANALYTICS_CLUSTERING_ADMIN: 'llm-analytics-clustering-admin', // owner: #team-ai-observability
LLM_ANALYTICS_CUSTOM_PARSERS: 'ai-observability-custom-parsers', // owner: #team-ai-observability
diff --git a/frontend/src/scenes/activity/live/LiveEventsTable.tsx b/frontend/src/scenes/activity/live/LiveEventsTable.tsx
index 3dd553d19bb0..c11366919db5 100644
--- a/frontend/src/scenes/activity/live/LiveEventsTable.tsx
+++ b/frontend/src/scenes/activity/live/LiveEventsTable.tsx
@@ -24,7 +24,7 @@ import { EventName } from 'products/actions/frontend/components/EventName'
import { LiveBotPanel } from './LiveBotPanel'
import { LiveEventsFeed } from './LiveEventsFeed'
-import { liveEventsLogic } from './liveEventsLogic'
+import { LIVE_EVENTS_SUPPORTED_OPERATORS, liveEventsLogic } from './liveEventsLogic'
import { liveEventsTableSceneLogic } from './liveEventsTableSceneLogic'
const LIVE_EVENTS_POLL_INTERVAL_MS = 1500
@@ -92,7 +92,11 @@ export function LiveEventsTable(): JSX.Element {
propertyFilters={filters.properties ?? []}
onChange={(properties) => setFilters({ ...filters, properties })}
taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}
- operatorAllowlist={[PropertyOperator.Exact]}
+ operatorAllowlist={
+ featureFlags[FEATURE_FLAGS.LIVE_EVENTS_RICH_FILTERS]
+ ? LIVE_EVENTS_SUPPORTED_OPERATORS
+ : [PropertyOperator.Exact]
+ }
buttonText="Filter by property"
/>
<LemonButton
diff --git a/frontend/src/scenes/activity/live/liveEventsLogic.test.ts b/frontend/src/scenes/activity/live/liveEventsLogic.test.ts
index 8885c5206ce1..4f50c119fb2c 100644
--- a/frontend/src/scenes/activity/live/liveEventsLogic.test.ts
+++ b/frontend/src/scenes/activity/live/liveEventsLogic.test.ts
@@ -1,7 +1,11 @@
import { expectLogic } from 'kea-test-utils'
+import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { initKeaTests } from '~/test/init'
-import { LiveEvent } from '~/types'
+import { AnyPropertyFilter, LiveEvent, PropertyFilterType, PropertyOperator } from '~/types'
import { liveEventsLogic } from './liveEventsLogic'
@@ -17,19 +21,45 @@ function makeLiveEvent(currentUrl?: string): LiveEvent {
}
}
+function eventFilter(key: string, operator: PropertyOperator, value?: AnyPropertyFilter['value']): AnyPropertyFilter {
+ return { type: PropertyFilterType.Event, key, operator, value } as AnyPropertyFilter
+}
+
describe('liveEventsLogic', () => {
let logic: ReturnType<typeof liveEventsLogic.build>
+ let flagsLogic: ReturnType<typeof featureFlagLogic.build>
+ let streamSpy: jest.SpyInstance
beforeEach(() => {
initKeaTests()
+ streamSpy = jest.spyOn(api, 'stream').mockResolvedValue(undefined as any)
+ flagsLogic = featureFlagLogic()
+ flagsLogic.mount()
logic = liveEventsLogic()
logic.mount()
})
afterEach(() => {
logic?.unmount()
+ flagsLogic?.unmount()
+ streamSpy.mockRestore()
})
+ function setRichFiltersFlag(enabled: boolean): void {
+ flagsLogic.actions.setFeatureFlags(
+ enabled ? [FEATURE_FLAGS.LIVE_EVENTS_RICH_FILTERS] : [],
+ enabled ? { [FEATURE_FLAGS.LIVE_EVENTS_RICH_FILTERS]: true } : {}
+ )
+ }
+
+ function lastStreamUrl(): URL {
+ const calls = streamSpy.mock.calls
+ if (calls.length === 0) {
+ throw new Error('api.stream was not called')
+ }
+ return new URL(calls[calls.length - 1][0] as string)
+ }
+
describe('addEvents host extraction', () => {
it('records the host for a valid $current_url', async () => {
await expectLogic(logic, () => {
@@ -51,4 +81,73 @@ describe('liveEventsLogic', () => {
})
})
})
+
+ describe('stream URL property filters', () => {
+ it.each([
+ {
+ label: 'emits legacy property= params and drops non-exact operators',
+ properties: [
+ eventFilter('$current_url', PropertyOperator.Exact, 'https://app.posthog.com'),
+ eventFilter('$browser', PropertyOperator.IContains, 'chrome'),
+ ],
+ expectedProperty: ['$current_url=https://app.posthog.com'],
+ },
+ {
+ label: 'expands a multi-value exact filter into repeated legacy params',
+ properties: [eventFilter('$browser', PropertyOperator.Exact, ['Chrome', 'Firefox'])],
+ expectedProperty: ['$browser=Chrome', '$browser=Firefox'],
+ },
+ ])('with the flag off, $label', ({ properties, expectedProperty }) => {
+ setRichFiltersFlag(false)
+ logic.actions.setFilters({ properties })
+
+ const url = lastStreamUrl()
+ expect(url.searchParams.getAll('property')).toEqual(expectedProperty)
+ expect(url.searchParams.has('properties')).toBe(false)
+ })
+
+ it.each([
+ {
+ label: 'emits a single JSON properties param',
+ properties: [
+ eventFilter('$current_url', PropertyOperator.IContains, 'checkout'),
+ eventFilter('$browser', PropertyOperator.Exact, ['Chrome', 'Firefox']),
+ eventFilter('amount', PropertyOperator.GreaterThan, 100),
+ eventFilter('$referrer', PropertyOperator.IsSet),
+ ],
+ expectedProperties: [
+ { key: '$current_url', operator: 'icontains', value: 'checkout' },
+ { key: '$browser', operator: 'exact', value: ['Chrome', 'Firefox'] },
+ { key: 'amount', operator: 'gt', value: 100 },
+ { key: '$referrer', operator: 'is_set' },
+ ],
+ },
+ {
+ label: 'skips null values, empty arrays, and unsupported operators',
+ properties: [
+ eventFilter('$current_url', PropertyOperator.Exact, null),
+ eventFilter('$browser', PropertyOperator.Exact, []),
+ eventFilter('$pathname', PropertyOperator.Between, '5'),
+ eventFilter('$os', PropertyOperator.IContains, 'mac'),
+ ],
+ expectedProperties: [{ key: '$os', operator: 'icontains', value: 'mac' }],
+ },
+ {
+ label: 'omits the properties param entirely when nothing is eligible',
+ properties: [eventFilter('$current_url', PropertyOperator.Exact, null)],
+ expectedProperties: null,
+ },
+ ])('with the flag on, $label', ({ properties, expectedProperties }) => {
+ setRichFiltersFlag(true)
+ logic.actions.setFilters({ properties })
+
+ const url = lastStreamUrl()
+ expect(url.searchParams.has('property')).toBe(false)
+ if (expectedProperties === null) {
+ expect(url.searchParams.has('properties')).toBe(false)
+ } else {
+ expect(JSON.parse(url.searchParams.get('properties')!)).toEqual(expectedProperties)
+ }
+ })
+ })
})
diff --git a/frontend/src/scenes/activity/live/liveEventsLogic.tsx b/frontend/src/scenes/activity/live/liveEventsLogic.tsx
index 5c1288a9c9ee..e1f50a59c508 100644
--- a/frontend/src/scenes/activity/live/liveEventsLogic.tsx
+++ b/frontend/src/scenes/activity/live/liveEventsLogic.tsx
@@ -4,16 +4,34 @@ import { Spinner, lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { isEventPropertyFilter } from 'lib/components/PropertyFilters/utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { liveEventsHostOrigin } from 'lib/utils/apiHost'
+import { isOperatorFlag } from 'lib/utils/operators'
import { teamLogic } from 'scenes/teamLogic'
-import { AnyPropertyFilter, LiveEvent, PropertyOperator } from '~/types'
+import { AnyPropertyFilter, LiveEvent, PropertyFilterValue, PropertyOperator } from '~/types'
import { deduplicateEvents } from './deduplicateEvents'
import type { liveEventsLogicType } from './liveEventsLogicType'
const ERROR_TOAST_ID = 'live-stream-error'
+export const LIVE_EVENTS_SUPPORTED_OPERATORS: PropertyOperator[] = [
+ PropertyOperator.Exact,
+ PropertyOperator.IsNot,
+ PropertyOperator.IContains,
+ PropertyOperator.NotIContains,
+ PropertyOperator.Regex,
+ PropertyOperator.NotRegex,
+ PropertyOperator.GreaterThan,
+ PropertyOperator.GreaterThanOrEqual,
+ PropertyOperator.LessThan,
+ PropertyOperator.LessThanOrEqual,
+ PropertyOperator.IsSet,
+ PropertyOperator.IsNotSet,
+]
+
export interface LiveEventsLogicProps {
showLiveStreamErrorToast?: boolean
}
@@ -22,7 +40,7 @@ export const liveEventsLogic = kea<liveEventsLogicType>([
path(['scenes', 'activity', 'live-events', 'liveEventsLogic']),
props({} as LiveEventsLogicProps),
connect(() => ({
- values: [teamLogic, ['currentTeam']],
+ values: [teamLogic, ['currentTeam'], featureFlagLogic, ['featureFlags']],
actions: [teamLogic, ['loadCurrentTeam']],
})),
actions(() => ({
@@ -122,16 +140,47 @@ export const liveEventsLogic = kea<liveEventsLogicType>([
if (eventType) {
url.searchParams.append('eventType', eventType)
}
- for (const pf of properties ?? []) {
- if (!isEventPropertyFilter(pf) || pf.operator !== PropertyOperator.Exact || !pf.key) {
- continue
+ if (values.featureFlags[FEATURE_FLAGS.LIVE_EVENTS_RICH_FILTERS]) {
+ const richFilters: { key: string; operator: PropertyOperator; value?: PropertyFilterValue }[] = []
+ for (const pf of properties ?? []) {
+ if (!isEventPropertyFilter(pf) || !pf.key || !pf.operator) {
+ continue
+ }
+ if (!LIVE_EVENTS_SUPPORTED_OPERATORS.includes(pf.operator)) {
+ continue
+ }
+ if (isOperatorFlag(pf.operator)) {
+ richFilters.push({ key: pf.key, operator: pf.operator })
+ continue
+ }
+ if (pf.value == null) {
+ continue
+ }
+ if (Array.isArray(pf.value)) {
+ const cleaned = pf.value.filter((v) => v != null)
+ if (cleaned.length === 0) {
+ continue
+ }
+ richFilters.push({ key: pf.key, operator: pf.operator, value: cleaned })
+ } else {
+ richFilters.push({ key: pf.key, operator: pf.operator, value: pf.value })
+ }
}
- const vals = Array.isArray(pf.value) ? pf.value : [pf.value]
- for (const v of vals) {
- if (v == null) {
+ if (richFilters.length > 0) {
+ url.searchParams.append('properties', JSON.stringify(richFilters))
+ }
+ } else {
+ for (const pf of properties ?? []) {
+ if (!isEventPropertyFilter(pf) || pf.operator !== PropertyOperator.Exact || !pf.key) {
continue
}
- url.searchParams.append('property', `${pf.key}=${String(v)}`)
+ const vals = Array.isArray(pf.value) ? pf.value : [pf.value]
+ for (const v of vals) {
+ if (v == null) {
+ continue
+ }
+ url.searchParams.append('property', `${pf.key}=${String(v)}`)
+ }
}
}
url.searchParams.append('columns', '$current_url,$screen_name')
diff --git a/livestream/events/filter.go b/livestream/events/filter.go
index a1528a61f37e..bd08059b221e 100644
--- a/livestream/events/filter.go
+++ b/livestream/events/filter.go
@@ -3,7 +3,10 @@ package events
import (
"fmt"
"log"
+ "regexp"
"slices"
+ "strconv"
+ "strings"
"sync/atomic"
"github.com/gofrs/uuid/v5"
@@ -11,6 +14,62 @@ import (
"github.com/prometheus/client_golang/prometheus"
)
+const (
+ OpExact = "exact"
+ OpIsNot = "is_not"
+ OpIContains = "icontains"
+ OpNotIContains = "not_icontains"
+ OpRegex = "regex"
+ OpNotRegex = "not_regex"
+ OpGreaterThan = "gt"
+ OpGreaterEqual = "gte"
+ OpLessThan = "lt"
+ OpLessEqual = "lte"
+ OpIsSet = "is_set"
+ OpIsNotSet = "is_not_set"
+)
+
+type CompiledPropertyFilter struct {
+ Key string
+ Operator string
+ Values []string
+
+ lowerValues []string
+ regexes []*regexp.Regexp
+ numbers []float64
+ numericOK []bool
+}
+
+func NewCompiledPropertyFilter(key, operator string, values []string) CompiledPropertyFilter {
+ f := CompiledPropertyFilter{Key: key, Operator: operator, Values: values}
+ switch operator {
+ case OpIContains, OpNotIContains:
+ f.lowerValues = make([]string, len(values))
+ for i, v := range values {
+ f.lowerValues[i] = strings.ToLower(v)
+ }
+ case OpRegex, OpNotRegex:
+ f.regexes = make([]*regexp.Regexp, len(values))
+ for i, v := range values {
+ if re, err := regexp.Compile(v); err == nil {
+ f.regexes[i] = re
+ } else {
+ log.Printf("WARNING: ignoring invalid regex in %s filter for key=%s value=%q: %v", operator, key, v, err)
+ }
+ }
+ case OpGreaterThan, OpGreaterEqual, OpLessThan, OpLessEqual:
+ f.numbers = make([]float64, len(values))
+ f.numericOK = make([]bool, len(values))
+ for i, v := range values {
+ if n, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil {
+ f.numbers[i] = n
+ f.numericOK[i] = true
+ }
+ }
+ }
+ return f
+}
+
type Subscription struct {
SubID uint64
@@ -19,7 +78,7 @@ type Subscription struct {
Token string
DistinctId string
EventTypes []string
- PropertyFilters map[string][]string
+ PropertyFilters []CompiledPropertyFilter
Geo bool
Columns []string
@@ -152,18 +211,113 @@ func (c *Filter) Run() {
}
}
-func matchesPropertyFilters(props map[string]interface{}, filters map[string][]string) bool {
- for key, allowed := range filters {
- raw, ok := props[key]
- if !ok {
+func matchesPropertyFilters(props map[string]interface{}, filters []CompiledPropertyFilter) bool {
+ for i := range filters {
+ if !filters[i].matches(props) {
+ return false
+ }
+ }
+ return true
+}
+
+func (f *CompiledPropertyFilter) hasValidRegex() bool {
+ for _, re := range f.regexes {
+ if re != nil {
+ return true
+ }
+ }
+ return false
+}
+
+func (f *CompiledPropertyFilter) matches(props map[string]interface{}) bool {
+ raw, present := props[f.Key]
+
+ switch f.Operator {
+ case OpIsSet:
+ return present
+ case OpIsNotSet:
+ return !present
+ }
+
+ if (f.Operator == OpRegex || f.Operator == OpNotRegex) && !f.hasValidRegex() {
+ return false
+ }
+
+ if !present {
+ switch f.Operator {
+ case OpIsNot, OpNotIContains, OpNotRegex:
+ return true
+ default:
return false
}
- actual := fmt.Sprint(raw)
- if !slices.Contains(allowed, actual) {
+ }
+
+ actual := fmt.Sprint(raw)
+
+ switch f.Operator {
+ case OpExact:
+ return slices.Contains(f.Values, actual)
+ case OpIsNot:
+ return !slices.Contains(f.Values, actual)
+ case OpIContains:
+ lower := strings.ToLower(actual)
+ for _, v := range f.lowerValues {
+ if strings.Contains(lower, v) {
+ return true
+ }
+ }
+ return false
+ case OpNotIContains:
+ lower := strings.ToLower(actual)
+ for _, v := range f.lowerValues {
+ if strings.Contains(lower, v) {
+ return false
+ }
+ }
+ return true
+ case OpRegex:
+ for _, re := range f.regexes {
+ if re != nil && re.MatchString(actual) {
+ return true
+ }
+ }
+ return false
+ case OpNotRegex:
+ for _, re := range f.regexes {
+ if re != nil && re.MatchString(actual) {
+ return false
+ }
+ }
+ return true
+ case OpGreaterThan, OpGreaterEqual, OpLessThan, OpLessEqual:
+ actualNum, err := strconv.ParseFloat(strings.TrimSpace(actual), 64)
+ if err != nil {
return false
}
+ for i, ok := range f.numericOK {
+ if ok && compareNumeric(f.Operator, actualNum, f.numbers[i]) {
+ return true
+ }
+ }
+ return false
+ default:
+ return false
+ }
+}
+
+func compareNumeric(operator string, actual, want float64) bool {
+ switch operator {
+ case OpGreaterThan:
+ return actual > want
+ case OpGreaterEqual:
+ return actual >= want
+ case OpLessThan:
+ return actual < want
+ case OpLessEqual:
+ return actual <= want
+ default:
+ return false
}
- return true
}
// Routes a single event to all matching subscriptions.
@@ -213,4 +367,3 @@ func deliverEvent(event PostHogEvent, subs []Subscription) {
}
}
}
-
diff --git a/livestream/events/filter_test.go b/livestream/events/filter_test.go
index 86f3e7b33563..31a7a69ba07b 100644
--- a/livestream/events/filter_test.go
+++ b/livestream/events/filter_test.go
@@ -208,7 +208,7 @@ func TestFilterRunWithMultipleSubscribersDifferentProperties(t *testing.T) {
EventChan: eventChan1,
ShouldClose: &atomic.Bool{},
DroppedEvents: &atomic.Uint64{},
- Columns: []string{"url"},
+ Columns: []string{"url"},
}
eventChan2 := make(chan interface{}, 1)
@@ -219,7 +219,7 @@ func TestFilterRunWithMultipleSubscribersDifferentProperties(t *testing.T) {
EventChan: eventChan2,
ShouldClose: &atomic.Bool{},
DroppedEvents: &atomic.Uint64{},
- Columns: []string{"url", "$browser"},
+ Columns: []string{"url", "$browser"},
}
eventChan3 := make(chan interface{}, 1)
@@ -230,7 +230,7 @@ func TestFilterRunWithMultipleSubscribersDifferentProperties(t *testing.T) {
EventChan: eventChan3,
ShouldClose: &atomic.Bool{},
DroppedEvents: &atomic.Uint64{},
- Columns: nil,
+ Columns: nil,
}
subChan <- sub1
@@ -298,61 +298,235 @@ func TestMatchesPropertyFilters(t *testing.T) {
tests := []struct {
name string
props map[string]interface{}
- filters map[string][]string
+ filters []CompiledPropertyFilter
want bool
}{
{
- name: "single key match",
+ name: "exact single key match",
props: map[string]interface{}{"$browser": "Chrome"},
- filters: map[string][]string{"$browser": {"Chrome"}},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpExact, []string{"Chrome"})},
want: true,
},
{
- name: "single key miss",
+ name: "exact single key miss",
props: map[string]interface{}{"$browser": "Firefox"},
- filters: map[string][]string{"$browser": {"Chrome"}},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpExact, []string{"Chrome"})},
want: false,
},
{
- name: "multiple values OR match",
+ name: "exact multiple values OR match",
props: map[string]interface{}{"$browser": "Firefox"},
- filters: map[string][]string{"$browser": {"Chrome", "Firefox"}},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpExact, []string{"Chrome", "Firefox"})},
want: true,
},
{
name: "multi-key AND match",
props: map[string]interface{}{"$browser": "Chrome", "plan": "enterprise"},
- filters: map[string][]string{
- "$browser": {"Chrome"},
- "plan": {"enterprise"},
+ filters: []CompiledPropertyFilter{
+ NewCompiledPropertyFilter("$browser", OpExact, []string{"Chrome"}),
+ NewCompiledPropertyFilter("plan", OpExact, []string{"enterprise"}),
},
want: true,
},
{
name: "multi-key AND miss on one key",
props: map[string]interface{}{"$browser": "Chrome", "plan": "free"},
- filters: map[string][]string{
- "$browser": {"Chrome"},
- "plan": {"enterprise"},
+ filters: []CompiledPropertyFilter{
+ NewCompiledPropertyFilter("$browser", OpExact, []string{"Chrome"}),
+ NewCompiledPropertyFilter("plan", OpExact, []string{"enterprise"}),
},
want: false,
},
{
- name: "missing key fails",
+ name: "exact missing key fails",
props: map[string]interface{}{"$os": "Linux"},
- filters: map[string][]string{"$browser": {"Chrome"}},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpExact, []string{"Chrome"})},
want: false,
},
{
- name: "numeric value coerced",
+ name: "numeric value coerced for exact",
props: map[string]interface{}{"count": 42},
- filters: map[string][]string{"count": {"42"}},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("count", OpExact, []string{"42"})},
want: true,
},
{
- name: "boolean value coerced",
+ name: "boolean value coerced for exact",
props: map[string]interface{}{"is_admin": true},
- filters: map[string][]string{"is_admin": {"true"}},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("is_admin", OpExact, []string{"true"})},
+ want: true,
+ },
+ {
+ name: "is_not match",
+ props: map[string]interface{}{"$browser": "Firefox"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsNot, []string{"Chrome"})},
+ want: true,
+ },
+ {
+ name: "is_not miss",
+ props: map[string]interface{}{"$browser": "Chrome"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsNot, []string{"Chrome"})},
+ want: false,
+ },
+ {
+ name: "is_not on missing key matches",
+ props: map[string]interface{}{"$os": "Linux"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsNot, []string{"Chrome"})},
+ want: true,
+ },
+ {
+ name: "is_not multi-value none match",
+ props: map[string]interface{}{"$browser": "Safari"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsNot, []string{"Chrome", "Firefox"})},
+ want: true,
+ },
+ {
+ name: "is_not multi-value one matches",
+ props: map[string]interface{}{"$browser": "Firefox"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsNot, []string{"Chrome", "Firefox"})},
+ want: false,
+ },
+ {
+ name: "icontains case-insensitive substring match",
+ props: map[string]interface{}{"$current_url": "https://app.posthog.com/CheckOut"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpIContains, []string{"checkout"})},
+ want: true,
+ },
+ {
+ name: "icontains miss",
+ props: map[string]interface{}{"$current_url": "https://app.posthog.com/insights"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpIContains, []string{"checkout"})},
+ want: false,
+ },
+ {
+ name: "not_icontains match",
+ props: map[string]interface{}{"$current_url": "https://app.posthog.com/insights"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpNotIContains, []string{"checkout"})},
+ want: true,
+ },
+ {
+ name: "not_icontains miss",
+ props: map[string]interface{}{"$current_url": "https://app.posthog.com/checkout"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpNotIContains, []string{"checkout"})},
+ want: false,
+ },
+ {
+ name: "not_icontains on missing key matches",
+ props: map[string]interface{}{"$os": "Linux"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpNotIContains, []string{"checkout"})},
+ want: true,
+ },
+ {
+ name: "regex match",
+ props: map[string]interface{}{"$current_url": "https://app.posthog.com/insights/123"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpRegex, []string{`/insights/\d+`})},
+ want: true,
+ },
+ {
+ name: "regex miss",
+ props: map[string]interface{}{"$current_url": "https://app.posthog.com/insights/abc"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpRegex, []string{`/insights/\d+`})},
+ want: false,
+ },
+ {
+ name: "invalid regex fails closed",
+ props: map[string]interface{}{"$current_url": "anything"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpRegex, []string{`(`})},
+ want: false,
+ },
+ {
+ name: "not_regex match",
+ props: map[string]interface{}{"$current_url": "https://app.posthog.com/insights/abc"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpNotRegex, []string{`/insights/\d+`})},
+ want: true,
+ },
+ {
+ name: "not_regex with invalid pattern fails closed",
+ props: map[string]interface{}{"$current_url": "anything"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpNotRegex, []string{`(`})},
+ want: false,
+ },
+ {
+ name: "not_regex with invalid pattern and missing property fails closed",
+ props: map[string]interface{}{},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$current_url", OpNotRegex, []string{`(`})},
+ want: false,
+ },
+ {
+ name: "gt numeric match",
+ props: map[string]interface{}{"count": 42},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("count", OpGreaterThan, []string{"10"})},
+ want: true,
+ },
+ {
+ name: "gt numeric miss",
+ props: map[string]interface{}{"count": 5},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("count", OpGreaterThan, []string{"10"})},
+ want: false,
+ },
+ {
+ name: "gte boundary match",
+ props: map[string]interface{}{"count": 10},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("count", OpGreaterEqual, []string{"10"})},
+ want: true,
+ },
+ {
+ name: "lt numeric match",
+ props: map[string]interface{}{"count": 3},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("count", OpLessThan, []string{"10"})},
+ want: true,
+ },
+ {
+ name: "lte boundary match",
+ props: map[string]interface{}{"count": 10},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("count", OpLessEqual, []string{"10"})},
+ want: true,
+ },
+ {
+ name: "numeric op on non-numeric event value fails",
+ props: map[string]interface{}{"count": "not-a-number"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("count", OpGreaterThan, []string{"10"})},
+ want: false,
+ },
+ {
+ name: "numeric op skips non-numeric filter value",
+ props: map[string]interface{}{"count": 42},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("count", OpGreaterThan, []string{"abc"})},
+ want: false,
+ },
+ {
+ name: "is_set on present key matches",
+ props: map[string]interface{}{"$browser": "Chrome"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsSet, nil)},
+ want: true,
+ },
+ {
+ name: "is_set on missing key fails",
+ props: map[string]interface{}{"$os": "Linux"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsSet, nil)},
+ want: false,
+ },
+ {
+ name: "is_not_set on missing key matches",
+ props: map[string]interface{}{"$os": "Linux"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsNotSet, nil)},
+ want: true,
+ },
+ {
+ name: "is_not_set on present key fails",
+ props: map[string]interface{}{"$browser": "Chrome"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpIsNotSet, nil)},
+ want: false,
+ },
+ {
+ name: "unknown operator fails closed",
+ props: map[string]interface{}{"$browser": "Chrome"},
+ filters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", "totally_made_up", []string{"Chrome"})},
+ want: false,
+ },
+ {
+ name: "no filters matches everything",
+ props: map[string]interface{}{"$browser": "Chrome"},
+ filters: nil,
want: true,
},
}
@@ -378,7 +552,7 @@ func TestFilterRunWithPropertyFilter(t *testing.T) {
SubID: 1,
TeamId: 1,
Token: "token1",
- PropertyFilters: map[string][]string{"$browser": {"Chrome"}},
+ PropertyFilters: []CompiledPropertyFilter{NewCompiledPropertyFilter("$browser", OpExact, []string{"Chrome"})},
EventChan: eventChan,
ShouldClose: &atomic.Bool{},
DroppedEvents: &atomic.Uint64{},
@@ -438,7 +612,7 @@ func TestFilterRunWithPropertyAndEventTypeFilter(t *testing.T) {
TeamId: 1,
Token: "token1",
EventTypes: []string{"checkout_completed"},
- PropertyFilters: map[string][]string{"plan": {"enterprise"}},
+ PropertyFilters: []CompiledPropertyFilter{NewCompiledPropertyFilter("plan", OpExact, []string{"enterprise"})},
EventChan: eventChan,
ShouldClose: &atomic.Bool{},
DroppedEvents: &atomic.Uint64{},
diff --git a/livestream/handlers/handlers.go b/livestream/handlers/handlers.go
index ac9b9c15bb35..b2453a09c56c 100644
--- a/livestream/handlers/handlers.go
+++ b/livestream/handlers/handlers.go
@@ -134,7 +134,7 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSu
eventTypes = strings.Split(eventType, ",")
}
- propertyFilters := parsePropertyFilters(c.QueryParams()["property"])
+ propertyFilters := parsePropertyFilters(c.QueryParam("properties"), c.QueryParams()["property"])
subscription := events.Subscription{
SubID: atomic.AddUint64(&subID, 1),
@@ -189,24 +189,80 @@ func StreamEventsHandler(log echo.Logger, subChan chan events.Subscription, unSu
}
}
-func parsePropertyFilters(raw []string) map[string][]string {
+func parsePropertyFilters(propertiesJSON string, legacy []string) []events.CompiledPropertyFilter {
+ filters := parsePropertyFiltersJSON(propertiesJSON)
+ filters = append(filters, parseLegacyPropertyFilters(legacy)...)
+ if len(filters) == 0 {
+ return nil
+ }
+ return filters
+}
+
+func parsePropertyFiltersJSON(raw string) []events.CompiledPropertyFilter {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return nil
+ }
+ dec := json.NewDecoder(strings.NewReader(raw))
+ dec.UseNumber()
+ var payloads []struct {
+ Key string `json:"key"`
+ Operator string `json:"operator"`
+ Value interface{} `json:"value"`
+ }
+ if err := dec.Decode(&payloads); err != nil {
+ return nil
+ }
+ out := make([]events.CompiledPropertyFilter, 0, len(payloads))
+ for _, p := range payloads {
+ if p.Key == "" || p.Operator == "" {
+ continue
+ }
+ out = append(out, events.NewCompiledPropertyFilter(p.Key, p.Operator, normalizeFilterValues(p.Value)))
+ }
+ return out
+}
+
+func parseLegacyPropertyFilters(raw []string) []events.CompiledPropertyFilter {
if len(raw) == 0 {
return nil
}
- out := make(map[string][]string, len(raw))
+ grouped := make(map[string][]string, len(raw))
+ order := make([]string, 0, len(raw))
for _, entry := range raw {
k, v, ok := strings.Cut(entry, "=")
if !ok || k == "" {
continue
}
- out[k] = append(out[k], v)
+ if _, seen := grouped[k]; !seen {
+ order = append(order, k)
+ }
+ grouped[k] = append(grouped[k], v)
}
- if len(out) == 0 {
- return nil
+ out := make([]events.CompiledPropertyFilter, 0, len(order))
+ for _, k := range order {
+ out = append(out, events.NewCompiledPropertyFilter(k, events.OpExact, grouped[k]))
}
return out
}
+func normalizeFilterValues(value interface{}) []string {
+ switch v := value.(type) {
+ case nil:
+ return nil
+ case []interface{}:
+ out := make([]string, 0, len(v))
+ for _, item := range v {
+ if item != nil {
+ out = append(out, fmt.Sprint(item))
+ }
+ }
+ return out
+ default:
+ return []string{fmt.Sprint(v)}
+ }
+}
+
func NotificationsHandler(redisClient rueidis.Client) func(c echo.Context) error {
return func(c echo.Context) error {
claims, err := auth.ParseAuthClaims(c.Request().Header)
diff --git a/livestream/handlers/handlers_test.go b/livestream/handlers/handlers_test.go
index be5b2974013f..9cc45c63212d 100644
--- a/livestream/handlers/handlers_test.go
+++ b/livestream/handlers/handlers_test.go
@@ -313,66 +313,123 @@ func TestFilterNotificationForUser(t *testing.T) {
}
}
+type filterShape struct {
+ Key string
+ Operator string
+ Values []string
+}
+
+func shapesOf(filters []events.CompiledPropertyFilter) []filterShape {
+ if filters == nil {
+ return nil
+ }
+ out := make([]filterShape, 0, len(filters))
+ for _, f := range filters {
+ out = append(out, filterShape{Key: f.Key, Operator: f.Operator, Values: f.Values})
+ }
+ return out
+}
+
func TestParsePropertyFilters(t *testing.T) {
tests := []struct {
- name string
- raw []string
- want map[string][]string
+ name string
+ propertiesJSON string
+ legacy []string
+ want []filterShape
}{
{
- name: "nil input",
- raw: nil,
+ name: "no input returns nil",
want: nil,
},
{
- name: "empty input",
- raw: []string{},
- want: nil,
+ name: "legacy single key=value as exact",
+ legacy: []string{"$browser=Chrome"},
+ want: []filterShape{{Key: "$browser", Operator: events.OpExact, Values: []string{"Chrome"}}},
},
{
- name: "single key=value",
- raw: []string{"$browser=Chrome"},
- want: map[string][]string{"$browser": {"Chrome"}},
+ name: "legacy multiple keys AND",
+ legacy: []string{"$browser=Chrome", "plan=enterprise"},
+ want: []filterShape{
+ {Key: "$browser", Operator: events.OpExact, Values: []string{"Chrome"}},
+ {Key: "plan", Operator: events.OpExact, Values: []string{"enterprise"}},
+ },
},
{
- name: "multiple keys AND",
- raw: []string{"$browser=Chrome", "plan=enterprise"},
- want: map[string][]string{
- "$browser": {"Chrome"},
- "plan": {"enterprise"},
- },
+ name: "legacy same key OR grouped",
+ legacy: []string{"$browser=Chrome", "$browser=Firefox"},
+ want: []filterShape{{Key: "$browser", Operator: events.OpExact, Values: []string{"Chrome", "Firefox"}}},
},
{
- name: "same key OR",
- raw: []string{"$browser=Chrome", "$browser=Firefox"},
- want: map[string][]string{"$browser": {"Chrome", "Firefox"}},
+ name: "legacy missing equals skipped",
+ legacy: []string{"$browser", "plan=free"},
+ want: []filterShape{{Key: "plan", Operator: events.OpExact, Values: []string{"free"}}},
},
{
- name: "missing equals skipped",
- raw: []string{"$browser", "plan=free"},
- want: map[string][]string{"plan": {"free"}},
+ name: "legacy all malformed returns nil",
+ legacy: []string{"=foo", "bar"},
+ want: nil,
},
{
- name: "empty key skipped",
- raw: []string{"=Chrome", "plan=free"},
- want: map[string][]string{"plan": {"free"}},
+ name: "json single icontains",
+ propertiesJSON: `[{"key":"$current_url","operator":"icontains","value":"checkout"}]`,
+ want: []filterShape{{Key: "$current_url", Operator: events.OpIContains, Values: []string{"checkout"}}},
},
{
- name: "all malformed returns nil",
- raw: []string{"=foo", "bar"},
- want: nil,
+ name: "json array value preserves order",
+ propertiesJSON: `[{"key":"$browser","operator":"exact","value":["Chrome","Firefox"]}]`,
+ want: []filterShape{{Key: "$browser", Operator: events.OpExact, Values: []string{"Chrome", "Firefox"}}},
+ },
+ {
+ name: "json numeric value not reformatted",
+ propertiesJSON: `[{"key":"count","operator":"gt","value":1000000}]`,
+ want: []filterShape{{Key: "count", Operator: events.OpGreaterThan, Values: []string{"1000000"}}},
},
{
- name: "empty value allowed",
- raw: []string{"plan="},
- want: map[string][]string{"plan": {""}},
+ name: "json is_set has no values",
+ propertiesJSON: `[{"key":"$browser","operator":"is_set"}]`,
+ want: []filterShape{{Key: "$browser", Operator: events.OpIsSet, Values: nil}},
+ },
+ {
+ name: "json null value yields nil values",
+ propertiesJSON: `[{"key":"$browser","operator":"exact","value":null}]`,
+ want: []filterShape{{Key: "$browser", Operator: events.OpExact, Values: nil}},
+ },
+ {
+ name: "json entry missing key skipped",
+ propertiesJSON: `[{"operator":"exact","value":"x"},{"key":"plan","operator":"exact","value":"free"}]`,
+ want: []filterShape{{Key: "plan", Operator: events.OpExact, Values: []string{"free"}}},
+ },
+ {
+ name: "json entry missing operator skipped",
+ propertiesJSON: `[{"key":"plan","value":"free"}]`,
+ want: nil,
+ },
+ {
+ name: "malformed json ignored",
+ propertiesJSON: `not json`,
+ want: nil,
+ },
+ {
+ name: "malformed json ignored but legacy still applies",
+ propertiesJSON: `{ broken`,
+ legacy: []string{"plan=free"},
+ want: []filterShape{{Key: "plan", Operator: events.OpExact, Values: []string{"free"}}},
+ },
+ {
+ name: "json and legacy merged, json first",
+ propertiesJSON: `[{"key":"$current_url","operator":"icontains","value":"checkout"}]`,
+ legacy: []string{"$browser=Chrome"},
+ want: []filterShape{
+ {Key: "$current_url", Operator: events.OpIContains, Values: []string{"checkout"}},
+ {Key: "$browser", Operator: events.OpExact, Values: []string{"Chrome"}},
+ },
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- got := parsePropertyFilters(tt.raw)
- assert.Equal(t, tt.want, got)
+ got := parsePropertyFilters(tt.propertiesJSON, tt.legacy)
+ assert.Equal(t, tt.want, shapesOf(got))
})
}
}