Skip to content

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

cohorts: port "never did this event", date-shape validation and the MV drop from main

Carl-Gerhard Lindesvärdcb158ee67f10
diff --git a/apps/start/src/components/cohort/cohort-criteria-builder.tsx b/apps/start/src/components/cohort/cohort-criteria-builder.tsx
index 9dbba726f..569af2a90 100644
--- a/apps/start/src/components/cohort/cohort-criteria-builder.tsx
+++ b/apps/start/src/components/cohort/cohort-criteria-builder.tsx
@@ -279,15 +279,19 @@ function EventCriteriaItem({
{ value: 'lte', label: 'At most' },
]}
label="Operator"
- onChange={(operator) =>
+ onChange={(operator) => {
+ const count = criteria.frequency?.count ?? 1;
onChange({
...criteria,
frequency: {
- ...(criteria.frequency ?? { count: 1 }),
operator,
+ // "At least 0" matches everyone and the server rejects it,
+ // so a count of 0 only survives the operators that mean
+ // "never".
+ count: operator === 'gte' && count === 0 ? 1 : count,
},
- })
- }
+ });
+ }}
>
<Button size="sm" variant="outline">
{criteria.frequency?.operator === 'gte' && 'At least'}
@@ -297,16 +301,26 @@ function EventCriteriaItem({
</DropdownMenuComposed>
<input
className="w-20 rounded border px-2 py-1 text-sm"
- min="1"
- onChange={(e) =>
+ min="0"
+ onChange={(e) => {
+ // Explicit NaN check, not `|| 1`: 0 is falsy, so the fallback
+ // rewrote a typed 0 back to 1 and "never did this event" could
+ // not be entered.
+ const parsed = Number.parseInt(e.target.value, 10);
+ const operator = criteria.frequency?.operator ?? 'gte';
onChange({
...criteria,
frequency: {
- operator: criteria.frequency?.operator ?? 'gte',
- count: Number.parseInt(e.target.value) || 1,
+ operator,
+ // Same "At least 0 matches everyone" clamp as the
+ // operator-change handler above.
+ count:
+ Number.isNaN(parsed) || (operator === 'gte' && parsed === 0)
+ ? 1
+ : parsed,
},
- })
- }
+ });
+ }}
type="number"
value={criteria.frequency?.count ?? 1}
/>
diff --git a/packages/core/src/modules/cohort/cohort.constants.test.ts b/packages/core/src/modules/cohort/cohort.constants.test.ts
new file mode 100644
index 000000000..f8403365c
--- /dev/null
+++ b/packages/core/src/modules/cohort/cohort.constants.test.ts
@@ -0,0 +1,74 @@
+// Ported from packages/validation/src/cohort.validation.test.ts (main #470,
+// #472).
+
+import { describe, expect, test } from 'bun:test';
+import { zAbsoluteTimeframe, zFrequency } from './cohort.constants';
+
+describe('zAbsoluteTimeframe', () => {
+ test('accepts a date without an end', () => {
+ expect(
+ zAbsoluteTimeframe.safeParse({ type: 'absolute', start: '2024-01-01' })
+ .success
+ ).toBe(true);
+ });
+
+ test('accepts a date range', () => {
+ expect(
+ zAbsoluteTimeframe.safeParse({
+ type: 'absolute',
+ start: '2024-01-01',
+ end: '2024-02-01',
+ }).success
+ ).toBe(true);
+ });
+
+ test.each(["2024-01-01') OR 1=1 --", '2024-1-1', 'yesterday', ''])(
+ 'rejects a non-date start (%s)',
+ (start) => {
+ expect(
+ zAbsoluteTimeframe.safeParse({ type: 'absolute', start }).success
+ ).toBe(false);
+ }
+ );
+
+ test('rejects a non-date end', () => {
+ expect(
+ zAbsoluteTimeframe.safeParse({
+ type: 'absolute',
+ start: '2024-01-01',
+ end: "2024-01-01') --",
+ }).success
+ ).toBe(false);
+ });
+});
+
+describe('zFrequency', () => {
+ test.each(['eq', 'lte'] as const)(
+ 'accepts a count of 0 with %s ("never did this event")',
+ (operator) => {
+ expect(zFrequency.safeParse({ operator, count: 0 }).success).toBe(true);
+ }
+ );
+
+ test('rejects a count of 0 with gte, which would match every profile', () => {
+ expect(zFrequency.safeParse({ operator: 'gte', count: 0 }).success).toBe(
+ false
+ );
+ });
+
+ test.each(['gte', 'eq', 'lte'] as const)(
+ 'still accepts positive counts with %s',
+ (operator) => {
+ expect(zFrequency.safeParse({ operator, count: 3 }).success).toBe(true);
+ }
+ );
+
+ test('still rejects negative and fractional counts', () => {
+ expect(zFrequency.safeParse({ operator: 'eq', count: -1 }).success).toBe(
+ false
+ );
+ expect(zFrequency.safeParse({ operator: 'eq', count: 1.5 }).success).toBe(
+ false
+ );
+ });
+});
diff --git a/packages/core/src/modules/cohort/cohort.constants.ts b/packages/core/src/modules/cohort/cohort.constants.ts
index 3eabb38d1..51fed8a48 100644
--- a/packages/core/src/modules/cohort/cohort.constants.ts
+++ b/packages/core/src/modules/cohort/cohort.constants.ts
@@ -21,10 +21,15 @@ export const zRelativeTimeframe = z.object({
value: z.enum(['7d', '30d', '90d', '180d', '365d']),
});
+// toDate() in the cohort query builder only understands plain calendar dates.
+const zDate = z
+ .string()
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'Expected a date in YYYY-MM-DD format');
+
export const zAbsoluteTimeframe = z.object({
type: z.literal('absolute'),
- start: z.string(),
- end: z.string().optional(),
+ start: zDate,
+ end: zDate.optional(),
});
export const zTimeframe = z.discriminatedUnion('type', [
@@ -34,10 +39,20 @@ export const zTimeframe = z.discriminatedUnion('type', [
export type Timeframe = z.infer<typeof zTimeframe>;
-export const zFrequency = z.object({
- operator: z.enum(['gte', 'eq', 'lte']),
- count: z.number().int().min(1),
-});
+// A count of 0 is how a criterion says "never did this event", so it has to
+// be accepted — but only with the two operators that read that way. `gte 0`
+// matches every profile, which is not a criterion at all, and letting it
+// through would leave the query builder with a third case to guess at.
+export const zFrequency = z
+ .object({
+ operator: z.enum(['gte', 'eq', 'lte']),
+ count: z.number().int().min(0),
+ })
+ .refine((frequency) => frequency.count > 0 || frequency.operator !== 'gte', {
+ message:
+ 'A count of 0 means "never", which only "exactly" and "at most" express',
+ path: ['count'],
+ });
export type Frequency = z.infer<typeof zFrequency>;
diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.ts
index cd7d71e66..1781e55bd 100644
--- a/packages/core/src/modules/cohort/cohort.service.ts
+++ b/packages/core/src/modules/cohort/cohort.service.ts
@@ -237,6 +237,44 @@ function eventPropertyCondition(filter: IChartEventFilter): SqlFragment {
}
}
+// "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
+// group that reaches the HAVING already has countMerge(event_count) >= 1 and
+// the criterion returns nothing. The query has to be inverted instead.
+//
+// `gte 0` is not "never" — it matches every profile — and zFrequency rejects
+// it, so it stays on the ordinary HAVING path.
+function isNeverFrequency(frequency: Frequency): boolean {
+ return (
+ frequency.count === 0 &&
+ (frequency.operator === 'eq' || frequency.operator === 'lte')
+ );
+}
+
+// Every profile in the project except the ones the summary MV knows about.
+// The timeframe stays inside the subquery, so "never did X in the last 30
+// days" keeps including someone who did X 60 days ago, matching how the
+// timeframe control reads for a positive criterion.
+//
+// DISTINCT rather than FINAL: profiles is a ReplacingMergeTree and FINAL
+// cannot spill to disk, so on wide projects the dedup is what runs out of
+// memory (same reason buildPropertyBasedCohortQuery groups instead of reading
+// through FINAL). Only the id is needed here, so deduplicating it is enough —
+// and the other branches of buildEventCriteriaQuery also emit one row per
+// profile, which the INTERSECT / UNION DISTINCT combination depends on.
+function buildNeverDidEventQuery(
+ projectId: string,
+ didEventQuery: SqlFragment
+): SqlFragment {
+ return sql`
+ SELECT DISTINCT id AS profile_id
+ FROM ${sql.id(TABLE.profiles)}
+ WHERE project_id = ${sql.string(projectId)}
+ AND id NOT IN (${didEventQuery})
+ `;
+}
+
export function buildEventCriteriaQuery(
projectId: string,
criteria: EventCriteria
@@ -262,6 +300,23 @@ export function buildEventCriteriaQuery(
);
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
@@ -286,6 +341,19 @@ export function buildEventCriteriaQuery(
}
if (frequency) {
+ if (isNeverFrequency(frequency)) {
+ return buildNeverDidEventQuery(
+ projectId,
+ sql`
+ SELECT profile_id
+ FROM ${sql.id(TABLE.eventProfileSummaryMv)}
+ WHERE project_id = ${project}
+ AND name = ${eventName}
+ AND ${timeConstraint}
+ `
+ );
+ }
+
const frequencyOp = getFrequencyOperator(frequency);
return sql`
SELECT profile_id
@@ -404,22 +472,38 @@ function combineCriteriaQueries(
);
}
-export async function computeEventBasedCohort(
- deps: ServiceDeps,
+// Every criterion emits one row per matching profile under the column name
+// profile_id, which is what lets them be combined as sets.
+export function buildEventBasedCohortQuery(
projectId: string,
- definition: EventBasedCohortDefinition,
- limit?: number
-): Promise<string[]> {
+ definition: EventBasedCohortDefinition
+): SqlFragment {
const { events, operator } = definition.criteria;
const queries = events.map((eventCriteria) =>
buildEventCriteriaQuery(projectId, eventCriteria)
);
- const combinedQuery = combineCriteriaQueries(queries, operator);
+ return combineCriteriaQueries(queries, operator);
+}
+export async function computeEventBasedCohort(
+ deps: ServiceDeps,
+ projectId: string,
+ definition: EventBasedCohortDefinition,
+ limit?: number
+): Promise<string[]> {
+ const combinedQuery = buildEventBasedCohortQuery(projectId, definition);
+
+ // The LIMIT has to wrap the combination, not trail it: appended to an
+ // INTERSECT / UNION chain, ClickHouse applies it to the last SELECT alone.
+ // That was survivable while every operand was a narrow event-derived set;
+ // a "never did X" operand is most of the project's profiles, so limiting it
+ // before the INTERSECT would cut the cohort down to an arbitrary slice —
+ // and at the preview's limit of 10, almost always to nothing. The count
+ // query below already wraps for the same reason.
const finalQuery = limit
- ? sql`${combinedQuery} LIMIT ${sql.uint64(limit)}`
+ ? sql`SELECT profile_id FROM (${combinedQuery}) LIMIT ${sql.uint64(limit)}`
: combinedQuery;
const results = await chQuery<{ profile_id: string }>(deps, finalQuery);
@@ -431,13 +515,7 @@ export async function countEventBasedCohort(
projectId: string,
definition: EventBasedCohortDefinition
): Promise<number> {
- const { events, operator } = definition.criteria;
-
- const queries = events.map((eventCriteria) =>
- buildEventCriteriaQuery(projectId, eventCriteria)
- );
-
- const combinedQuery = combineCriteriaQueries(queries, operator);
+ const combinedQuery = buildEventBasedCohortQuery(projectId, definition);
const countQuery = sql`SELECT count() as count FROM (${combinedQuery})`;
const results = await chQuery<{ count: number }>(deps, countQuery);
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
new file mode 100644
index 000000000..5dfac60cd
--- /dev/null
+++ b/packages/core/src/modules/cohort/src/cohort-event-sql.test.ts
@@ -0,0 +1,285 @@
+// SQL-shape tests for event-based cohort criteria. Ported from
+// packages/db/src/services/cohort.service.test.ts (main #470, #472): the
+// timeframe and project id are bound as `{pN:String}` params here rather than
+// escaped into the text, so the hostile-value assertions check the binding —
+// the value is absent from the rendered SQL and present, verbatim, in the
+// params. The "never did this event" assertions are unchanged in what they
+// claim.
+
+import { describe, expect, test } from 'bun:test';
+import type {
+ EventBasedCohortDefinition,
+ EventCriteria,
+} from '../cohort.constants';
+import {
+ buildEventBasedCohortQuery,
+ buildEventCriteriaQuery,
+} from '../cohort.service';
+
+const PROJECT_ID = 'test-cohort-timeframe';
+
+function criteria(timeframe: EventCriteria['timeframe']): EventCriteria {
+ return { name: 'screen_view', filters: [], timeframe };
+}
+
+function render(fragment: ReturnType<typeof buildEventCriteriaQuery>) {
+ return fragment.toStatement();
+}
+
+// Values that would break out of a naive `toDate('${value}')` interpolation.
+const HOSTILE = [
+ "2024-01-01') OR 1=1 --",
+ "2024-01-01'",
+ "2024-01-01') UNION ALL SELECT id FROM profiles --",
+];
+
+describe('buildEventCriteriaQuery timeframe binding', () => {
+ test.each(HOSTILE)('binds a hostile start (%s)', (start) => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(PROJECT_ID, criteria({ type: 'absolute', start }))
+ );
+
+ expect(query).toContain('event_date >= toDate({p3:String})');
+ expect(query).not.toContain(start);
+ expect(query).not.toMatch(/OR 1=1|UNION ALL/);
+ expect(query_params.p3).toBe(start);
+ });
+
+ test.each(HOSTILE)('binds a hostile end (%s)', (end) => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ criteria({ type: 'absolute', start: '2024-01-01', end })
+ )
+ );
+
+ expect(query).toContain(
+ 'event_date BETWEEN toDate({p3:String}) AND toDate({p4:String})'
+ );
+ expect(query).not.toContain(end);
+ expect(query_params.p3).toBe('2024-01-01');
+ expect(query_params.p4).toBe(end);
+ });
+
+ test('binds the project id too', () => {
+ const hostile = "p9' OR 1=1 --";
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ hostile,
+ criteria({ type: 'absolute', start: '2024-01-01' })
+ )
+ );
+
+ expect(query).toContain('project_id = {p1:String}');
+ expect(query).not.toContain(hostile);
+ expect(query_params.p1).toBe(hostile);
+ });
+
+ test('still builds relative timeframes', () => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ criteria({ type: 'relative', value: '30d' })
+ )
+ );
+
+ expect(query).toContain(
+ 'event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY)'
+ );
+ expect(query_params.p3).toBe(30);
+ });
+});
+
+const LAST_30_DAYS = {
+ type: 'relative',
+ value: '30d',
+} satisfies EventCriteria['timeframe'];
+
+function frequencyCriteria(
+ frequency: EventCriteria['frequency'],
+ filters: EventCriteria['filters'] = []
+): EventCriteria {
+ return {
+ name: 'subscription_started',
+ filters,
+ timeframe: LAST_30_DAYS,
+ frequency,
+ };
+}
+
+// Everything the outer profile scan sees, i.e. the query with the NOT IN
+// subquery cut out.
+function outsideExclusion(query: string): string {
+ const open = query.indexOf('NOT IN (');
+ if (open === -1) {
+ return query;
+ }
+ return query.slice(0, open) + query.slice(query.lastIndexOf(')') + 1);
+}
+
+describe('buildEventCriteriaQuery zero frequency', () => {
+ test.each(['eq', 'lte'] as const)(
+ 'excludes anyone who did the event when the count is 0 (%s)',
+ (operator) => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator, count: 0 })
+ )
+ );
+
+ // The summary MV has no row for zero occurrences, so a HAVING can never
+ // match here — the query has to be inverted.
+ expect(query).not.toContain('HAVING');
+ expect(query).toContain('SELECT DISTINCT id AS profile_id');
+ expect(query).toContain('FROM profiles');
+ expect(query).toContain('NOT IN (');
+ expect(query).toContain('FROM event_profile_summary_mv');
+ expect(query).toContain('name = {p3:String}');
+ expect(query_params.p3).toBe('subscription_started');
+ }
+ );
+
+ test('gives eq 0 and lte 0 the same query', () => {
+ expect(
+ render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'eq', count: 0 })
+ )
+ )
+ ).toEqual(
+ render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'lte', count: 0 })
+ )
+ )
+ );
+ });
+
+ test('keeps the timeframe inside the exclusion, not on the profile scan', () => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'eq', count: 0 })
+ )
+ );
+
+ // "Never did X in the last 30 days" still includes someone who did X 60
+ // days ago — which only holds while the date bound sits in the subquery.
+ expect(query).toContain(
+ 'event_date >= toDate(now() - INTERVAL {p4:UInt64} DAY)'
+ );
+ expect(query_params.p4).toBe(30);
+ expect(outsideExclusion(query)).not.toContain('event_date');
+ expect(outsideExclusion(query)).toContain('project_id = {p1:String}');
+ expect(query_params.p1).toBe(PROJECT_ID);
+ });
+
+ test('excludes on the matching property row when the criterion has property filters', () => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'eq', count: 0 }, [
+ {
+ id: 'plan',
+ name: 'properties.plan',
+ operator: 'is',
+ value: ['pro'],
+ },
+ ])
+ )
+ );
+
+ // Read as "has no matching (event, property) row": 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_params.p5).toBe('plan');
+ expect(outsideExclusion(query)).not.toContain('property_key');
+ });
+
+ test('leaves gte 0 on the ordinary path (zFrequency rejects it upstream)', () => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator: 'gte', count: 0 })
+ )
+ );
+
+ expect(query).toContain('HAVING countMerge(event_count) >= {p4:UInt64}');
+ expect(query_params.p4).toBe(0);
+ expect(query).not.toContain('NOT IN');
+ });
+
+ test.each([
+ ['gte', 1, '>='],
+ ['eq', 2, '='],
+ ['lte', 3, '<='],
+ ] as const)(
+ 'still groups and filters for positive counts (%s %i)',
+ (operator, count, comparison) => {
+ const { query, query_params } = render(
+ buildEventCriteriaQuery(
+ PROJECT_ID,
+ frequencyCriteria({ operator, count })
+ )
+ );
+
+ expect(query).toContain('GROUP BY profile_id');
+ expect(query).toContain(
+ `HAVING countMerge(event_count) ${comparison} {p4:UInt64}`
+ );
+ expect(query_params.p4).toBe(count);
+ expect(query).not.toContain('FROM profiles');
+ }
+ );
+});
+
+describe('buildEventBasedCohortQuery with a zero-count criterion', () => {
+ const definition = {
+ type: 'event',
+ criteria: {
+ operator: 'and',
+ events: [
+ {
+ name: 'signup',
+ filters: [],
+ timeframe: LAST_30_DAYS,
+ frequency: { operator: 'gte', count: 1 },
+ },
+ frequencyCriteria({ operator: 'eq', count: 0 }),
+ ],
+ },
+ } satisfies EventBasedCohortDefinition;
+
+ test('intersects two sets of profile_id', () => {
+ const { query } = render(
+ buildEventBasedCohortQuery(PROJECT_ID, definition)
+ );
+ const [signedUp, neverSubscribed] = query.split(' INTERSECT ');
+
+ expect(neverSubscribed).toBeDefined();
+ // Both operands have to be a bare set of profile_id for the INTERSECT to
+ // mean anything: same column name, one row per profile, no LIMIT or
+ // ORDER BY of their own.
+ expect(signedUp).toContain('SELECT profile_id');
+ expect(neverSubscribed).toContain('SELECT DISTINCT id AS profile_id');
+ expect(query).not.toContain('ORDER BY');
+ expect(query).not.toContain('LIMIT');
+ });
+
+ test('unions them under "or"', () => {
+ const { query } = render(
+ buildEventBasedCohortQuery(PROJECT_ID, {
+ ...definition,
+ criteria: { ...definition.criteria, operator: 'or' },
+ })
+ );
+
+ expect(query).toContain(' UNION DISTINCT ');
+ expect(query).not.toContain(' INTERSECT ');
+ });
+});
diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.ts
index 4b5907147..e3fedc4ec 100644
--- a/packages/core/src/modules/organization/organization.service.ts
+++ b/packages/core/src/modules/organization/organization.service.ts
@@ -537,8 +537,6 @@ export async function deleteFromClickhouse(
TABLE_NAMES.event_property_values_mv,
TABLE_NAMES.cohort_members,
TABLE_NAMES.cohort_metadata,
- TABLE_NAMES.profile_event_summary_mv,
- TABLE_NAMES.profile_event_property_summary_mv,
TABLE_NAMES.event_profile_summary_mv,
TABLE_NAMES.event_property_profile_summary_mv,
];
diff --git a/packages/core/src/shared/ch-tables.ts b/packages/core/src/shared/ch-tables.ts
index ed3527202..abc19d8b6 100644
--- a/packages/core/src/shared/ch-tables.ts
+++ b/packages/core/src/shared/ch-tables.ts
@@ -32,6 +32,8 @@ export const TABLE_NAMES = {
groups: 'groups',
cohort_members: 'cohort_members',
cohort_metadata: 'cohort_metadata',
+ // Superseded by the two event_*_summary_mv entries below and dropped in
+ // migration 24. Kept because migrations 13, 14 and 15 still name them.
profile_event_summary_mv: 'profile_event_summary_mv',
// Same content as the two MVs above, keyed for the cohort criteria that
// read them (event + window first, profile last) rather than by profile.
diff --git a/packages/db/src/clickhouse/client.ts b/packages/db/src/clickhouse/client.ts
index 70b4675c3..cb50b86a6 100644
--- a/packages/db/src/clickhouse/client.ts
+++ b/packages/db/src/clickhouse/client.ts
@@ -68,6 +68,8 @@ export const TABLE_NAMES = {
groups: 'groups',
cohort_members: 'cohort_members',
cohort_metadata: 'cohort_metadata',
+ // Superseded by the two event_*_summary_mv entries below and dropped in
+ // migration 24. Kept because migrations 13, 14 and 15 still name them.
profile_event_summary_mv: 'profile_event_summary_mv',
// Same content as the two MVs above, keyed for the cohort criteria that
// read them (event + window first, profile last) rather than by profile.
diff --git a/packages/db/src/code-migrations/24-drop-old-cohort-summary-mvs.ts b/packages/db/src/code-migrations/24-drop-old-cohort-summary-mvs.ts
new file mode 100644
index 000000000..d86b8c443
--- /dev/null
+++ b/packages/db/src/code-migrations/24-drop-old-cohort-summary-mvs.ts
@@ -0,0 +1,48 @@
+import { TABLE_NAMES } from '../clickhouse/client';
+import {
+ dropTable,
+ runClickhouseMigrationCommands,
+} from '../clickhouse/migration';
+import { type CodeMigrationEnv, getIsCluster } from './helpers';
+
+/**
+ * Drop the profile-keyed cohort summary MVs superseded by migration 20.
+ *
+ * - profile_event_summary_mv (created in migration 13)
+ * - profile_event_property_summary_mv (created in migration 14)
+ *
+ * Migration 20 created replacements keyed for the queries that read them,
+ * migration 21 filled them with history, and cohort.service has read the new
+ * tables since. The old pair kept receiving inserts so the change stayed
+ * revertible by pointer while the new tables were verified. Nothing reads
+ * them now, so they are two MV triggers firing on every event insert for no
+ * consumer.
+ *
+ * Clustered installs have two objects per MV: `<name>` is the Distributed
+ * table and `<name>_replicated` is the materialized view itself. The
+ * Distributed table goes first so nothing can route a read at a view that is
+ * mid-drop. Dropping the view takes its implicit `.inner_id.<uuid>` storage
+ * with it, so there is no third name to clean up.
+ *
+ * Deliberately one-way. The aggregated history goes with the tables, and
+ * rerunning migrations 13 and 14 would only bring back empty structure, so a
+ * down() would be a rollback in name only. If you need them back, those two
+ * migrations hold the definitions and migration 15 the backfill.
+ */
+
+const SUPERSEDED_MVS = [
+ TABLE_NAMES.profile_event_summary_mv,
+ TABLE_NAMES.profile_event_property_summary_mv,
+];
+
+export async function up(env: CodeMigrationEnv) {
+ const isClustered = getIsCluster(env);
+
+ const sqls = SUPERSEDED_MVS.flatMap((name) =>
+ isClustered
+ ? [dropTable(name, true), dropTable(`${name}_replicated`, true)]
+ : [dropTable(name, false)]
+ );
+
+ await runClickhouseMigrationCommands(sqls);
+}