Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix(cohorts): event cohort filters on columns and properties now narrow the members (#624)

Carl-Gerhard Lindesvärd8c1fd7e18b28
diff --git a/packages/core/src/modules/chart/src/filter-where.test.ts b/packages/core/src/modules/chart/src/filter-where.test.ts
new file mode 100644
index 000000000..3aca50043
--- /dev/null
+++ b/packages/core/src/modules/chart/src/filter-where.test.ts
@@ -0,0 +1,72 @@
+// Shape tests for the operators of the shared event filter compiler whose
+// meaning is easy to get backwards.
+
+import { describe, expect, test } from 'bun:test';
+import type { IChartEventFilter } from '../../report/report.constants';
+import { getEventFiltersWhereClause, joinFilterClauses } from './filter-where';
+
+const PROJECT_ID = 'filter-where-test';
+
+function render(filters: IChartEventFilter[]) {
+ const clause = joinFilterClauses(
+ getEventFiltersWhereClause(filters, PROJECT_ID)
+ );
+ if (!clause) {
+ throw new Error('expected a clause');
+ }
+ return clause.toStatement();
+}
+
+const filter = (
+ name: string,
+ operator: IChartEventFilter['operator'],
+ value: string[]
+): IChartEventFilter => ({ id: 'f', name, operator, value });
+
+// "Does not contain a or b" means "contains neither". The negation of an
+// any-of (`contains`) is a none-of, so the NOT LIKEs must AND: OR-ed, a path
+// that contains only one of the values would match.
+describe('doesNotContain with several values', () => {
+ test('ANDs the NOT LIKEs on a bare column', () => {
+ const { query, query_params } = render([
+ filter('path', 'doesNotContain', ['/admin', '/debug']),
+ ]);
+
+ expect(query).toBe(
+ '(path NOT LIKE {p1:String} AND path NOT LIKE {p2:String})'
+ );
+ expect(query_params).toEqual({ p1: '%/admin%', p2: '%/debug%' });
+ });
+
+ test('ANDs the NOT LIKEs on an event property', () => {
+ const { query } = render([
+ filter('properties.plan', 'doesNotContain', ['free', 'trial']),
+ ]);
+
+ expect(query).toContain(
+ 'NOT LIKE {p2:String} AND properties[{p3:String}] NOT LIKE {p4:String}'
+ );
+ expect(query).not.toContain(' OR ');
+ });
+
+ test('ANDs the NOT LIKEs on a group property', () => {
+ const { query } = render([
+ filter('group.company.tier', 'doesNotContain', ['free', 'trial']),
+ ]);
+
+ expect(query).toContain(' AND ');
+ expect(query).not.toContain(' OR ');
+ });
+
+ test('leaves a single value as one NOT LIKE', () => {
+ const { query } = render([filter('path', 'doesNotContain', ['/admin'])]);
+
+ expect(query).toBe('(path NOT LIKE {p1:String})');
+ });
+
+ test('contains stays any-of', () => {
+ const { query } = render([filter('path', 'contains', ['/a', '/b'])]);
+
+ expect(query).toBe('(path LIKE {p1:String} OR path LIKE {p2:String})');
+ });
+});
diff --git a/packages/core/src/modules/chart/src/filter-where.ts b/packages/core/src/modules/chart/src/filter-where.ts
index 18c9687cb..943971c61 100644
--- a/packages/core/src/modules/chart/src/filter-where.ts
+++ b/packages/core/src/modules/chart/src/filter-where.ts
@@ -57,6 +57,11 @@ function anyOf(clauses: SqlFragment[]): SqlFragment {
return sql`(${sql.join(clauses, ' OR ')})`;
}
+/** The negation of `anyOf`: "does not contain a or b" is "contains neither". */
+function noneOf(clauses: SqlFragment[]): SqlFragment {
+ return sql`(${sql.join(clauses, ' AND ')})`;
+}
+
/** No outer parentheses, unlike `anyOf` — `arrayExists` already wraps its predicate. */
function anyItem(clauses: SqlFragment[], haystack: SqlSlot): SqlFragment {
return sql`arrayExists(x -> ${sql.join(clauses, ' OR ')}, ${haystack})`;
@@ -211,7 +216,7 @@ export function getEventFiltersWhereClause(
break;
}
case 'doesNotContain': {
- where[id] = anyOf(
+ where[id] = noneOf(
value.map(
(val) =>
sql`${whereFrom} NOT LIKE ${sql.string(`%${String(val).trim()}%`)}`
@@ -329,7 +334,7 @@ export function getEventFiltersWhereClause(
value.map((val) => sql`x NOT LIKE ${like(val)}`),
whereFrom
)
- : anyOf(
+ : noneOf(
value.map((val) => sql`${whereFrom} NOT LIKE ${like(val)}`)
);
break;
@@ -516,7 +521,7 @@ export function getEventFiltersWhereClause(
break;
}
case 'doesNotContain': {
- where[id] = anyOf(
+ where[id] = noneOf(
value.map(
(val) =>
sql`${column} NOT LIKE ${sql.string(`%${String(val).trim()}%`)}`
diff --git a/packages/core/src/modules/cohort/cohort.constants.test.ts b/packages/core/src/modules/cohort/cohort.constants.test.ts
index 346b27846..c1fdd6056 100644
--- a/packages/core/src/modules/cohort/cohort.constants.test.ts
+++ b/packages/core/src/modules/cohort/cohort.constants.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, test } from 'bun:test';
-import { zAbsoluteTimeframe, zFrequency } from './cohort.constants';
+import {
+ zAbsoluteTimeframe,
+ zEventCriteria,
+ zFrequency,
+} from './cohort.constants';
describe('zAbsoluteTimeframe', () => {
test('accepts a date without an end', () => {
@@ -72,3 +76,36 @@ describe('zFrequency', () => {
);
});
});
+
+describe('zEventCriteria filters', () => {
+ const criteria = (name: string) => ({
+ name: 'purchase',
+ timeframe: { type: 'relative', value: '30d' },
+ filters: [{ id: 'f', name, operator: 'is', value: ['x'] }],
+ });
+
+ test.each([
+ 'path',
+ 'has_profile',
+ 'properties.plan',
+ 'profile.email',
+ 'profile.properties.plan',
+ 'session.duration',
+ ])('accepts a filter name the schema cannot rule out (%s)', (name) => {
+ expect(zEventCriteria.safeParse(criteria(name)).success).toBe(true);
+ });
+
+ // Group and wildcard profile filters read joins only the chart engine
+ // builds; letting them through would fail the refresh job in ClickHouse.
+ test.each([
+ 'group.name',
+ 'group.properties.tier',
+ 'profile.properties.*',
+ ])('rejects a filter that needs a join (%s)', (name) => {
+ const result = zEventCriteria.safeParse(criteria(name));
+ expect(result.success).toBe(false);
+ expect(JSON.stringify(result.error?.issues)).toContain(
+ 'not supported in event cohorts'
+ );
+ });
+});
diff --git a/packages/core/src/modules/cohort/cohort.constants.ts b/packages/core/src/modules/cohort/cohort.constants.ts
index dbc5dbe58..3e2c50806 100644
--- a/packages/core/src/modules/cohort/cohort.constants.ts
+++ b/packages/core/src/modules/cohort/cohort.constants.ts
@@ -41,11 +41,36 @@ export const zFrequency = z
export type Frequency = z.infer<typeof zFrequency>;
+// An event criterion is evaluated on the events table alone. Group filters
+// and wildcard profile filters compile against joins only the chart engine
+// builds, so they are refused here; the service also refuses any filter the
+// compiler cannot turn into a clause.
+const GROUP_FILTER_PREFIX = 'group.';
+const PROFILE_FILTER_PREFIXES = ['profile.', 'profiles.'] as const;
+
+export function isUnsupportedEventCohortFilter(name: string): boolean {
+ if (name.startsWith(GROUP_FILTER_PREFIX)) {
+ return true;
+ }
+ const isProfileFilter = PROFILE_FILTER_PREFIXES.some((prefix) =>
+ name.startsWith(prefix)
+ );
+ return isProfileFilter && name.includes('*');
+}
+
+export const UNSUPPORTED_EVENT_COHORT_FILTER_MESSAGE =
+ 'This filter is not supported in event cohorts';
+
export const zEventCriteria = z.object({
name: z.string().min(1).describe('The event name to match'),
filters: z
.array(zChartEventFilter)
.default([])
+ .refine(
+ (filters) =>
+ !filters.some((filter) => isUnsupportedEventCohortFilter(filter.name)),
+ { message: UNSUPPORTED_EVENT_COHORT_FILTER_MESSAGE }
+ )
.describe('Filters applied to event properties'),
timeframe: zTimeframe.describe('When the event should have occurred'),
frequency: zFrequency
diff --git a/packages/core/src/modules/cohort/cohort.rpc.ts b/packages/core/src/modules/cohort/cohort.rpc.ts
index b54f468dc..999436a55 100644
--- a/packages/core/src/modules/cohort/cohort.rpc.ts
+++ b/packages/core/src/modules/cohort/cohort.rpc.ts
@@ -4,7 +4,7 @@
import { z } from 'zod';
import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
-import { TRPCNotFoundError } from '../../rpc/errors';
+import { TRPCBadRequestError, TRPCNotFoundError } from '../../rpc/errors';
import { getSettingsForProject } from '../organization/organization.service';
import { zChartEventFilter, zRange } from '../report/report.constants';
import { getChartStartEndDate } from '../report/src/chart-dates';
@@ -14,6 +14,7 @@ import {
zCohortUpdate,
} from './cohort.constants';
import {
+ assertCohortDefinitionSupported,
computeCohort,
countCohort,
deleteCohortMembership,
@@ -23,6 +24,7 @@ import {
getCohortMemberRoutes,
getCohortMembers,
listCohortMemberProfiles,
+ UnsupportedCohortFilterError,
} from './cohort.service';
const EXPORT_PROFILES_MAX_LIMIT = 10_000;
@@ -34,6 +36,22 @@ const EXPORT_PROFILES_DEFAULT_LIMIT = 10_000;
*/
const COHORT_ACTIVITY_DEFAULT_RANGE = '3m';
+// Refused on save and preview, so the builder shows why instead of the refresh
+// job failing later or, worse, the cohort matching everyone.
+function requireSupportedDefinition(
+ projectId: string,
+ definition: Parameters<typeof assertCohortDefinitionSupported>[1]
+): void {
+ try {
+ assertCohortDefinitionSupported(projectId, definition);
+ } catch (error) {
+ if (error instanceof UnsupportedCohortFilterError) {
+ throw new TRPCBadRequestError(error.message);
+ }
+ throw error;
+ }
+}
+
const zCohortActivityInput = z.object({
projectId: z.string(),
cohortId: z.string(),
@@ -105,6 +123,7 @@ export const cohortRouter = createTRPCRouter({
projectId: input.projectId,
level: 'write',
});
+ requireSupportedDefinition(input.projectId, input.definition);
const db = ctx.db;
const cohort = await db.cohort.create({
@@ -140,6 +159,9 @@ export const cohortRouter = createTRPCRouter({
projectId: existingCohort.projectId,
level: 'write',
});
+ if (data.definition) {
+ requireSupportedDefinition(existingCohort.projectId, data.definition);
+ }
const cohort = await db.cohort.update({
where: { id },
@@ -302,6 +324,7 @@ export const cohortRouter = createTRPCRouter({
projectId: input.projectId,
level: 'read',
});
+ requireSupportedDefinition(input.projectId, input.definition);
const count = await countCohort(ctx, input.projectId, input.definition);
const sampleProfiles = await computeCohort(
diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.ts
index 0f880513c..c8eff6d4c 100644
--- a/packages/core/src/modules/cohort/cohort.service.ts
+++ b/packages/core/src/modules/cohort/cohort.service.ts
@@ -12,15 +12,21 @@ import type { ServiceDeps, Services } from '../../services';
import { formatClickhouseDate } from '../../shared/ch-dates';
import { replicatedTarget } from '../../shared/ch-tables';
import { PROFILE_SELECT_COLUMNS } from '../chart/chart.constants';
+import {
+ getEventFiltersWhereClause,
+ joinFilterClauses,
+} from '../chart/src/filter-where';
import type { IServiceProfile } from '../profile/profile.service';
import type { IChartEventFilter } from '../report/report.constants';
-import type {
- CohortDefinition,
- EventBasedCohortDefinition,
- EventCriteria,
- Frequency,
- PropertyBasedCohortDefinition,
- Timeframe,
+import {
+ type CohortDefinition,
+ type EventBasedCohortDefinition,
+ type EventCriteria,
+ type Frequency,
+ isUnsupportedEventCohortFilter,
+ type PropertyBasedCohortDefinition,
+ type Timeframe,
+ UNSUPPORTED_EVENT_COHORT_FILTER_MESSAGE,
} from './cohort.constants';
// Physical ClickHouse table names this module reads/writes.
@@ -30,7 +36,6 @@ const TABLE = {
cohortMembers: 'cohort_members',
cohortMetadata: 'cohort_metadata',
eventProfileSummaryMv: 'event_profile_summary_mv',
- eventPropertyProfileSummaryMv: 'event_property_profile_summary_mv',
} as const;
// Max members materialized into cohort_members per compute. Larger cohorts are
@@ -132,46 +137,6 @@ function trimmedComparand(value: unknown): string {
return String(value).trim();
}
-// One event-property filter. Values bind; the property key is a Map key, so it
-// binds as a value too. An `IN`/`NOT IN` list becomes one `Array(String)`
-// param; an empty list matches nothing.
-function eventPropertyCondition(filter: IChartEventFilter): SqlFragment {
- const propertyKey = sql.string(filter.name.replace('properties.', ''));
- const { value, operator } = filter;
- const list = sql.array('String', value.map(trimmedComparand));
-
- switch (operator) {
- case 'is':
- if (value.length === 1) {
- return sql`(property_key = ${propertyKey} AND property_value = ${sql.string(trimmedComparand(value[0]))})`;
- }
- return sql`(property_key = ${propertyKey} AND property_value IN ${list})`;
- case 'isNot':
- if (value.length === 1) {
- return sql`(property_key = ${propertyKey} AND property_value != ${sql.string(trimmedComparand(value[0]))})`;
- }
- return sql`(property_key = ${propertyKey} AND property_value NOT IN ${list})`;
- case 'contains':
- return sql`(property_key = ${propertyKey} AND (${sql.join(
- value.map(
- (val) =>
- sql`property_value LIKE ${sql.string(`%${trimmedComparand(val)}%`)}`
- ),
- ' OR '
- )}))`;
- case 'doesNotContain':
- return sql`(property_key = ${propertyKey} AND (${sql.join(
- value.map(
- (val) =>
- sql`property_value NOT LIKE ${sql.string(`%${trimmedComparand(val)}%`)}`
- ),
- ' AND '
- )}))`;
- default:
- return sql`(property_key = ${propertyKey} AND property_value IN ${list})`;
- }
-}
-
// "Exactly 0" and "at most 0" both mean the profile never did the event.
// Neither can be expressed as a HAVING on the summary MVs: those hold a row
// only for a (project, profile, event, day) that actually happened, so every
@@ -210,67 +175,130 @@ function buildNeverDidEventQuery(
`;
}
-export function buildEventCriteriaQuery(
+// A filtered criterion reads the events table with the same filter compiler
+// every report uses, so a cohort filter means exactly what it means in a
+// report: bare columns (path, country, has_profile), `properties.*` with every
+// operator, nested cohorts, and several filters AND-ed on one event. The
+// summary MVs cannot express that: they hold no columns, and one row per
+// property key, so they stay reserved for the unfiltered criteria below.
+//
+// `profile_id != device_id` keeps the MVs' identified-only membership.
+function buildFilteredEventCriteriaQuery(
projectId: string,
- criteria: EventCriteria
+ criteria: EventCriteria,
+ filterWhere: SqlFragment
): SqlFragment {
- const { name, filters, timeframe, frequency } = criteria;
- const timeConstraint = buildTimeConstraint(timeframe, sql.id('event_date'));
- const project = sql.string(projectId);
- const eventName = sql.string(name);
- const hasEventPropertyFilters = filters.some((f) =>
- f.name.startsWith('properties.')
+ const { name, timeframe, frequency } = criteria;
+ // toDate(created_at) is the second sort-key column, so the window prunes.
+ const timeConstraint = buildTimeConstraint(
+ timeframe,
+ sql`toDate(created_at)`
);
+ const matchingEvents = sql`
+ FROM ${sql.id(TABLE.events)}
+ WHERE project_id = ${sql.string(projectId)}
+ AND name = ${sql.string(name)}
+ AND ${timeConstraint}
+ AND profile_id != device_id
+ AND ${filterWhere}
+ `;
- if (hasEventPropertyFilters) {
- const propertyConditions = sql.join(
- filters
- .filter((f) => f.name.startsWith('properties.'))
- .map(eventPropertyCondition),
- ' OR '
+ if (frequency && isNeverFrequency(frequency)) {
+ // "Never did X where plan = pro" reads as "has no matching event", so the
+ // filters go inside the exclusion: someone who did X with plan = free is a
+ // member.
+ return buildNeverDidEventQuery(
+ projectId,
+ sql`SELECT DISTINCT profile_id ${matchingEvents}`
);
+ }
- if (frequency) {
- if (isNeverFrequency(frequency)) {
- // "Never did X where plan = pro" reads as "has no matching (event,
- // property) row", so the property predicates go inside the exclusion:
- // someone who did the event with plan = free is a member.
- return buildNeverDidEventQuery(
- projectId,
- sql`
- SELECT profile_id
- FROM ${sql.id(TABLE.eventPropertyProfileSummaryMv)}
- WHERE project_id = ${project}
- AND name = ${eventName}
- AND ${timeConstraint}
- AND (${propertyConditions})
- `
- );
- }
-
- const frequencyOp = getFrequencyOperator(frequency);
- return sql`
- SELECT profile_id
- FROM ${sql.id(TABLE.eventPropertyProfileSummaryMv)}
- WHERE project_id = ${project}
- AND name = ${eventName}
- AND ${timeConstraint}
- AND (${propertyConditions})
- GROUP BY profile_id
- HAVING countMerge(event_count) ${frequencyOp}
- `;
- }
-
+ if (frequency) {
return sql`
- SELECT DISTINCT profile_id
- FROM ${sql.id(TABLE.eventPropertyProfileSummaryMv)}
- WHERE project_id = ${project}
- AND name = ${eventName}
- AND ${timeConstraint}
- AND (${propertyConditions})
+ SELECT profile_id
+ ${matchingEvents}
+ GROUP BY profile_id
+ HAVING count() ${getFrequencyOperator(frequency)}
`;
}
+ return sql`SELECT DISTINCT profile_id ${matchingEvents}`;
+}
+
+/** A cohort filter the events-table query cannot evaluate. */
+export class UnsupportedCohortFilterError extends Error {
+ readonly filterName: string;
+
+ constructor(filterName: string) {
+ super(`${UNSUPPORTED_EVENT_COHORT_FILTER_MESSAGE}: ${filterName}`);
+ this.name = 'UnsupportedCohortFilterError';
+ this.filterName = filterName;
+ }
+}
+
+// A row the builder shows before a value is picked has nothing to compare
+// against, so it narrows nothing, as in a report.
+function hasComparand(filter: IChartEventFilter): boolean {
+ return (
+ filter.value.length > 0 ||
+ filter.operator === 'isNull' ||
+ filter.operator === 'isNotNull'
+ );
+}
+
+// Every filter with a value must become a clause. The compiler silently skips
+// names it cannot resolve (`session.entry_path`, a typo), and a skipped filter
+// would leave the criterion matching everyone who did the event — the exact
+// failure this module once had for `path`. Group and wildcard profile filters
+// do compile, but against joins this query does not build.
+function compileEventCriteriaFilters(
+ projectId: string,
+ filters: IChartEventFilter[]
+): SqlFragment | null {
+ const activeFilters = filters.filter(hasComparand);
+ const unsupportedByName = activeFilters.find((filter) =>
+ isUnsupportedEventCohortFilter(filter.name)
+ );
+ if (unsupportedByName) {
+ throw new UnsupportedCohortFilterError(unsupportedByName.name);
+ }
+
+ const compiled = getEventFiltersWhereClause(activeFilters, projectId);
+ const dropped = activeFilters.find((_, index) => !compiled[`f${index}`]);
+ if (dropped) {
+ throw new UnsupportedCohortFilterError(dropped.name);
+ }
+ return joinFilterClauses(compiled);
+}
+
+/** Throws UnsupportedCohortFilterError when a criterion cannot be evaluated. */
+export function assertCohortDefinitionSupported(
+ projectId: string,
+ definition: CohortDefinition
+): void {
+ if (definition.type !== 'event') {
+ return;
+ }
+ for (const criteria of definition.criteria.events) {
+ compileEventCriteriaFilters(projectId, criteria.filters);
+ }
+}
+
+export function buildEventCriteriaQuery(
+ projectId: string,
+ criteria: EventCriteria
+): SqlFragment {
+ const { name, filters, timeframe, frequency } = criteria;
+
+ const filterWhere = compileEventCriteriaFilters(projectId, filters);
+ if (filterWhere) {
+ return buildFilteredEventCriteriaQuery(projectId, criteria, filterWhere);
+ }
+
+ const timeConstraint = buildTimeConstraint(timeframe, sql.id('event_date'));
+ const project = sql.string(projectId);
+ const eventName = sql.string(name);
+
if (frequency) {
if (isNeverFrequency(frequency)) {
return buildNeverDidEventQuery(
@@ -512,7 +540,7 @@ function getProfileFiltersWhereClause(
(val) =>
sql`${columnAccess} NOT LIKE ${sql.string(`%${trimmedComparand(val)}%`)}`
),
- ' OR '
+ ' AND '
)})`;
break;
}
diff --git a/packages/core/src/modules/cohort/src/cohort-event-sql.test.ts b/packages/core/src/modules/cohort/src/cohort-event-sql.test.ts
index 556782000..7516afefc 100644
--- a/packages/core/src/modules/cohort/src/cohort-event-sql.test.ts
+++ b/packages/core/src/modules/cohort/src/cohort-event-sql.test.ts
@@ -6,8 +6,10 @@ import type {
EventCriteria,
} from '../cohort.constants';
import {
+ assertCohortDefinitionSupported,
buildEventBasedCohortQuery,
buildEventCriteriaQuery,
+ UnsupportedCohortFilterError,
} from '../cohort.service';
const PROJECT_ID = 'test-cohort-timeframe';
@@ -171,7 +173,7 @@ describe('buildEventCriteriaQuery zero frequency', () => {
expect(query_params.p1).toBe(PROJECT_ID);
});
- test('excludes on the matching property row when the criterion has property filters', () => {
+ test('excludes on the matching events when the criterion has filters', () => {
const { query, query_params } = render(
buildEventCriteriaQuery(
PROJECT_ID,
@@ -186,13 +188,15 @@ describe('buildEventCriteriaQuery zero frequency', () => {
)
);
- // Read as "has no matching (event, property) row": someone who did the
- // event with plan = free is a member.
+ // Read as "has no matching event": someone who did the event with
+ // plan = free is a member.
expect(query).not.toContain('HAVING');
- expect(query).toContain('FROM event_property_profile_summary_mv');
- expect(query).toContain('property_key = {p5:String}');
+ expect(query).toContain('NOT IN (SELECT DISTINCT profile_id');
+ expect(query).toContain('FROM events');
+ expect(query).toContain('properties[{p5:String}] = {p6:String}');
expect(query_params.p5).toBe('plan');
- expect(outsideExclusion(query)).not.toContain('property_key');
+ expect(query_params.p6).toBe('pro');
+ expect(outsideExclusion(query)).not.toContain('properties[');
});
test('leaves gte 0 on the ordinary path (zFrequency rejects it upstream)', () => {
@@ -274,3 +278,230 @@ describe('buildEventBasedCohortQuery with a zero-count criterion', () => {
expect(query).not.toContain(' INTERSECT ');
});
});
+
+// A filtered criterion has to read the events table: the summary MVs hold no
+// columns (path, country, has_profile) and one row per property key, so they
+// can neither apply a column filter nor AND two property filters. Before this
+// split, a `path` filter was silently dropped and the cohort matched everyone
+// who did the event at all.
+describe('buildEventCriteriaQuery with filters', () => {
+ const pathFilter = {
+ id: 'path',
+ name: 'path',
+ operator: 'startsWith',
+ value: ['/db'],
+ } satisfies EventCriteria['filters'][number];
+
+ const hasProfileFilter = {
+ id: 'has_profile',
+ name: 'has_profile',
+ operator: 'is',
+ value: ['true'],
+ } satisfies EventCriteria['filters'][number];
+
+ test('applies a bare column filter on the events table', () => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 }, [pathFilter])
+ )
+ );
+
+ expect(query).toContain('FROM events');
+ expect(query).not.toContain('_summary_mv');
+ expect(query).toContain('name = {p2:String}');
+ expect(query).toContain(
+ 'toDate(created_at) >= toDate(now() - INTERVAL {p3:UInt64} DAY)'
+ );
+ expect(query).toContain('path LIKE {p4:String}');
+ expect(query_params.p4).toBe('/db%');
+ expect(query).toContain('GROUP BY profile_id');
+ expect(query).toContain('HAVING count() >= {p5:UInt64}');
+ expect(query_params.p5).toBe(1);
+ });
+
+ test('keeps membership identified-only, like the summary MVs', () => {
+ const { query } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 }, [pathFilter])
+ )
+ );
+
+ expect(query).toContain('profile_id != device_id');
+ });
+
+ test('ANDs several filters on the same event', () => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 }, [
+ {
+ id: 'plan',
+ name: 'properties.plan',
+ operator: 'is',
+ value: ['pro'],
+ },
+ { id: 'country', name: 'country', operator: 'is', value: ['SE'] },
+ ])
+ )
+ );
+
+ expect(query).toContain(
+ 'properties[{p4:String}] = {p5:String} AND country = {p6:String}'
+ );
+ expect(query_params.p4).toBe('plan');
+ expect(query_params.p5).toBe('pro');
+ expect(query_params.p6).toBe('SE');
+ });
+
+ test('gives a property filter every operator a report has', () => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria(undefined, [
+ {
+ id: 'plan',
+ name: 'properties.plan',
+ operator: 'startsWith',
+ value: ['pr'],
+ },
+ ])
+ )
+ );
+
+ expect(query).toContain('SELECT DISTINCT profile_id');
+ expect(query).toContain('properties[{p4:String}] LIKE {p5:String}');
+ expect(query_params.p5).toBe('pr%');
+ expect(query).not.toContain('HAVING');
+ });
+
+ test('a has_profile filter compiles rather than being dropped', () => {
+ const { query } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 }, [
+ pathFilter,
+ hasProfileFilter,
+ ])
+ )
+ );
+
+ expect(query).toContain('FROM events');
+ // The compiled has_profile clause sits after the path clause; the
+ // unconditional identified-only predicate alone would not prove it.
+ expect(query).toContain(
+ '(path LIKE {p4:String}) AND profile_id != device_id'
+ );
+ });
+
+ test('a profile property filter compiles to a profiles subquery, no join', () => {
+ const { query } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 }, [
+ {
+ id: 'plan',
+ name: 'profile.properties.plan',
+ operator: 'is',
+ value: ['pro'],
+ },
+ ])
+ )
+ );
+
+ expect(query).toContain('FROM events');
+ expect(query).toContain('cityHash64(profile_id) IN (');
+ expect(query).toContain('FROM profiles');
+ expect(query).not.toContain('JOIN');
+ });
+
+ // A filter that does not become a clause would leave the criterion matching
+ // everyone who did the event, so anything the query cannot evaluate is
+ // refused instead.
+ test.each([
+ ['group.name', 'needs the groups join'],
+ ['profile.properties.*', 'needs the profile join'],
+ ['session.entry_path', 'is skipped by the compiler'],
+ ['session.country', 'is skipped by the compiler'],
+ ['temple_name', 'is an unknown field'],
+ ])('refuses %s, which %s', (name) => {
+ const build = () =>
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 }, [
+ pathFilter,
+ { id: 'x', name, operator: 'is', value: ['x'] },
+ ])
+ );
+
+ expect(build).toThrow(UnsupportedCohortFilterError);
+ expect(build).toThrow(`not supported in event cohorts: ${name}`);
+ });
+
+ test('a row without a value yet narrows nothing and leaves the summary MV', () => {
+ const { query } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 }, [
+ { id: 'empty', name: 'path', operator: 'is', value: [] },
+ ])
+ )
+ );
+
+ expect(query).toContain('FROM event_profile_summary_mv');
+ expect(query).not.toContain('FROM events');
+ });
+
+ test('a row without a value yet does not hide the filters that have one', () => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 }, [
+ { id: 'empty', name: 'path', operator: 'is', value: [] },
+ { id: 'c', name: 'country', operator: 'is', value: ['SE'] },
+ ])
+ )
+ );
+
+ expect(query).toContain('FROM events');
+ expect(query).toContain('country = {p4:String}');
+ expect(query_params.p4).toBe('SE');
+ });
+
+ test('assertCohortDefinitionSupported checks every criterion', () => {
+ const definition = {
+ type: 'event',
+ criteria: {
+ operator: 'and',
+ events: [
+ frequencyCriteria({ operator: 'gte', count: 1 }, [pathFilter]),
+ frequencyCriteria({ operator: 'gte', count: 1 }, [
+ {
+ id: 's',
+ name: 'session.entry_path',
+ operator: 'is',
+ value: ['/'],
+ },
+ ]),
+ ],
+ },
+ } satisfies EventBasedCohortDefinition;
+
+ expect(() =>
+ assertCohortDefinitionSupported(PROJECT_ID, definition)
+ ).toThrow(UnsupportedCohortFilterError);
+ });
+
+ test('an unfiltered criterion still reads the summary MV', () => {
+ const { query } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 1 })
+ )
+ );
+
+ expect(query).toContain('FROM event_profile_summary_mv');
+ expect(query).toContain('HAVING countMerge(event_count) >= {p4:UInt64}');
+ });
+});
diff --git a/packages/core/src/modules/cohort/src/event-cohort-membership.test.ts b/packages/core/src/modules/cohort/src/event-cohort-membership.test.ts
new file mode 100644
index 000000000..4e74eca9e
--- /dev/null
+++ b/packages/core/src/modules/cohort/src/event-cohort-membership.test.ts
@@ -0,0 +1,195 @@
+// Integration test for event cohorts with filters against the isolated
+// `openpanel_test` ClickHouse (pinned by test/preload.ts).
+//
+// Fixture (test/fixtures.ts): Alice — page_view /home 2 days ago (Chrome);
+// Charlie — screen_view + page_view /shop 5 days ago (Firefox), purchase;
+// Bob — no events. This suite adds one page_view for Alice carrying
+// `properties.plan = pro`.
+
+import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
+import {
+ pinFixtureClock,
+ releaseFixtureClock,
+} from '../../../../test/fixture-clock';
+import type { EventCriteria } from '../cohort.constants';
+
+const TEST_PROJECT_ID = 'cohort-event-filters-test';
+const LAST_30_DAYS = { type: 'relative', value: '30d' } as const;
+const ALICE_PRO_EVENT_ID = '00000000-0000-0000-0000-00000000c0f1';
+
+let FIXTURE: typeof import('../../../../../../test/fixtures').FIXTURE;
+let subject: typeof import('../cohort.service');
+let deps: import('../../../services').ServiceDeps;
+
+beforeAll(async () => {
+ const fixtures = await import('../../../../../../test/fixtures');
+ FIXTURE = fixtures.FIXTURE;
+ const { bootstrapTestDatabases } = await import(
+ '../../../../../../test/bootstrap-databases'
+ );
+ await bootstrapTestDatabases();
+ const { testServiceDeps } = await import('../../../../test/service-deps');
+ deps = await testServiceDeps();
+ subject = await import('../cohort.service');
+
+ const now = pinFixtureClock();
+ await fixtures.setupFixtures(TEST_PROJECT_ID);
+ await deps.ch.insert({
+ table: 'events',
+ values: [
+ fixtures.buildEvent(
+ now,
+ TEST_PROJECT_ID,
+ ALICE_PRO_EVENT_ID,
+ 'page_view',
+ FIXTURE.profiles.alice,
+ FIXTURE.sessions.alice1,
+ 2,
+ 1,
+ { path: '/pricing', properties: { plan: 'pro' } }
+ ),
+ ],
+ format: 'JSONEachRow',
+ });
+});
+
+afterAll(async () => {
+ const fixtures = await import('../../../../../../test/fixtures');
+ await fixtures.teardownFixtures(TEST_PROJECT_ID);
+ releaseFixtureClock();
+});
+
+function members(criteria: EventCriteria): Promise<string[]> {
+ return subject
+ .computeEventBasedCohort(deps, TEST_PROJECT_ID, {
+ type: 'event',
+ criteria: { operator: 'and', events: [criteria] },
+ })
+ .then((ids) => ids.sort());
+}
+
+describe('event cohort membership with filters', () => {
+ it('matches everyone who did the event when there is no filter', async () => {
+ expect(
+ await members({ name: 'page_view', filters: [], timeframe: LAST_30_DAYS })
+ ).toEqual([FIXTURE.profiles.alice, FIXTURE.profiles.charlie]);
+ });
+
+ it('narrows by a path prefix', async () => {
+ expect(
+ await members({
+ name: 'page_view',
+ filters: [
+ { id: 'f', name: 'path', operator: 'startsWith', value: ['/sh'] },
+ ],
+ timeframe: LAST_30_DAYS,
+ frequency: { operator: 'gte', count: 1 },
+ })
+ ).toEqual([FIXTURE.profiles.charlie]);
+ });
+
+ it('narrows by a bare column alongside has_profile', async () => {
+ expect(
+ await members({
+ name: 'page_view',
+ filters: [
+ { id: 'b', name: 'browser', operator: 'is', value: ['Chrome'] },
+ { id: 'p', name: 'has_profile', operator: 'is', value: ['true'] },
+ ],
+ timeframe: LAST_30_DAYS,
+ })
+ ).toEqual([FIXTURE.profiles.alice]);
+ });
+
+ it('narrows by an event property with a non-equality operator', async () => {
+ expect(
+ await members({
+ name: 'page_view',
+ filters: [
+ {
+ id: 'f',
+ name: 'properties.plan',
+ operator: 'startsWith',
+ value: ['pr'],
+ },
+ ],
+ timeframe: LAST_30_DAYS,
+ })
+ ).toEqual([FIXTURE.profiles.alice]);
+ });
+
+ it('ANDs two filters on the same event', async () => {
+ expect(
+ await members({
+ name: 'page_view',
+ filters: [
+ { id: 'f', name: 'properties.plan', operator: 'is', value: ['pro'] },
+ { id: 'g', name: 'path', operator: 'is', value: ['/home'] },
+ ],
+ timeframe: LAST_30_DAYS,
+ })
+ ).toEqual([]);
+ });
+
+ it('does not contain several values means contains none of them', async () => {
+ // Alice: /home and /pricing; Charlie: /shop. OR-ed NOT LIKEs would let
+ // Charlie's /shop event through on the /pri half.
+ expect(
+ await members({
+ name: 'page_view',
+ filters: [
+ {
+ id: 'f',
+ name: 'path',
+ operator: 'doesNotContain',
+ value: ['/sh', '/pri'],
+ },
+ ],
+ timeframe: LAST_30_DAYS,
+ })
+ ).toEqual([FIXTURE.profiles.alice]);
+ });
+
+ it('narrows by a profile property through the profiles subquery', async () => {
+ expect(
+ await members({
+ name: 'page_view',
+ filters: [
+ {
+ id: 'f',
+ name: 'profile.properties.browser',
+ operator: 'is',
+ value: ['Firefox'],
+ },
+ ],
+ timeframe: LAST_30_DAYS,
+ })
+ ).toEqual([FIXTURE.profiles.charlie]);
+ });
+
+ it('counts events, not property rows, for the frequency', async () => {
+ expect(
+ await members({
+ name: 'page_view',
+ filters: [
+ { id: 'f', name: 'browser', operator: 'is', value: ['Chrome'] },
+ ],
+ timeframe: LAST_30_DAYS,
+ frequency: { operator: 'eq', count: 2 },
+ })
+ ).toEqual([FIXTURE.profiles.alice]);
+ });
+
+ it('inverts a never-did criterion around the filtered events', async () => {
+ expect(
+ await members({
+ name: 'page_view',
+ filters: [
+ { id: 'f', name: 'path', operator: 'startsWith', value: ['/sh'] },
+ ],
+ timeframe: LAST_30_DAYS,
+ frequency: { operator: 'eq', count: 0 },
+ })
+ ).toEqual([FIXTURE.profiles.alice, FIXTURE.profiles.bob]);
+ });
+});