Skip to content

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

fix(funnel): attribute breakdowns at the entry step instead of grouping by them (#436)

Ritik Jain12d8c4a71478
diff --git a/packages/db/src/services/funnel-sql.test.ts b/packages/db/src/services/funnel-sql.test.ts
index 35fc8e097..36bb2c8e9 100644
--- a/packages/db/src/services/funnel-sql.test.ts
+++ b/packages/db/src/services/funnel-sql.test.ts
@@ -201,13 +201,51 @@ describe('funnel.service / buildFunnelBase — unknown breakdowns', () => {
// Both sides must resolve the same breakdown to the same b_N index,
// otherwise the breakdownValues filter targets the wrong column.
- expect(chartSql).toContain("profile.properties['plan'] as b_0");
- expect(profilesSql).toContain("profile.properties['plan'] as b_0");
+ expect(chartSql).toContain(
+ "argMinIf(profile.properties['plan'], created_at,",
+ );
+ expect(profilesSql).toContain(
+ "argMinIf(profile.properties['plan'], created_at,",
+ );
await explain(chartSql);
await explain(profilesSql);
});
});
+describe('funnel.service / buildFunnelBase — breakdown attribution', () => {
+ // The breakdown value must be read at the user's FIRST funnel step, not
+ // used as a windowFunnel GROUP BY key. Per-row grouping splits a user's
+ // steps across buckets whenever the property isn't identical on every
+ // step, so the sequence never connects and downstream steps show 0.
+ it('attributes event-property breakdowns at the entry step', async () => {
+ const sql = await buildChartSql([breakdown('properties.experiment')]);
+ expect(sql).toContain("argMinIf(properties['experiment'], created_at,");
+ // The windowFunnel aggregation groups by the primary key only; b_0 is an
+ // aggregate, not a grouping key. (The outer chart GROUP BY level, b_0 is
+ // unaffected.)
+ expect(sql).toMatch(/GROUP BY session_id\b/);
+ expect(sql).not.toMatch(/GROUP BY session_id, b_0/);
+ });
+
+ itCH('entry-step attribution parses and resolves', async () => {
+ const sql = await buildChartSql([breakdown('properties.experiment')]);
+ await explain(sql);
+ });
+
+ it('keeps per-row grouping for group breakdowns (fan-out is intended)', async () => {
+ // A user in three groups should appear in all three funnels, so group.*
+ // breakdowns keep the ARRAY JOIN fan-out and per-row GROUP BY.
+ const sql = await buildChartSql([breakdown('group.plan')]);
+ expect(sql).not.toContain('argMinIf');
+ expect(sql).toMatch(/GROUP BY session_id, b_0/);
+ });
+
+ itCH('group-breakdown SQL parses and resolves', async () => {
+ const sql = await buildChartSql([breakdown('group.plan')]);
+ await explain(sql);
+ });
+});
+
describe('funnel.service / buildFunnelBase — group breakdowns', () => {
itCH('adds the group array join for a group breakdown', async () => {
const sql = await buildProfilesSql([breakdown('group.plan')]);
diff --git a/packages/db/src/services/funnel.service.ts b/packages/db/src/services/funnel.service.ts
index 8f61b9ab3..9790de67b 100644
--- a/packages/db/src/services/funnel.service.ts
+++ b/packages/db/src/services/funnel.service.ts
@@ -288,12 +288,42 @@ export class FunnelService {
const cohortIds = collectBreakdownCohortIds(breakdowns);
const cohortMetadata = await fetchCohortsMetadata(cohortIds);
+ // Attribute each breakdown to its value at the user's FIRST funnel step,
+ // as a per-group aggregate (argMinIf) — not by adding it to the
+ // windowFunnel GROUP BY. Grouping the sequence by a per-row value splits
+ // a user's steps across buckets whenever the value isn't identical on
+ // every step (e.g. an experiment tag set on the entry event but absent
+ // on the conversion event): the later step lands in a separate bucket,
+ // the windowFunnel sequence never connects, and downstream steps show 0.
+ // Reading the entry-step value keeps each sequence intact in one bucket
+ // and matches standard funnel-breakdown semantics (segment by entry
+ // attribute).
+ //
+ // `group.*` breakdowns are the exception: their ARRAY JOIN fans each
+ // event out per group, and grouping by the group value is intentional —
+ // a user in three groups should appear in all three funnels. Those keep
+ // the per-row GROUP BY.
+ const firstStepCondition = this.getFunnelConditions(
+ eventSeries,
+ projectId,
+ )[0]!;
const breakdownSelects = breakdowns.map((b, index) => {
const bId = extractCohortId(b.name);
const bName = bId ? cohortMetadata.get(bId)?.name : undefined;
- return `${getSelectPropertyKey(b.name, projectId, bId ?? undefined, bName)} as b_${index}`;
+ const expr = getSelectPropertyKey(
+ b.name,
+ projectId,
+ bId ?? undefined,
+ bName,
+ );
+ if (b.name.startsWith('group.')) {
+ return `${expr} as b_${index}`;
+ }
+ return `argMinIf(${expr}, created_at, ${firstStepCondition}) as b_${index}`;
});
- const breakdownGroupBy = breakdowns.map((_, index) => `b_${index}`);
+ const breakdownGroupBy = breakdowns.flatMap((b, index) =>
+ b.name.startsWith('group.') ? [`b_${index}`] : [],
+ );
const funnelCte = this.buildFunnelCte({
projectId,
diff --git a/packages/trpc/src/routers/chart.ts b/packages/trpc/src/routers/chart.ts
index 20240a33e..88cc29f14 100644
--- a/packages/trpc/src/routers/chart.ts
+++ b/packages/trpc/src/routers/chart.ts
@@ -6,6 +6,7 @@ import {
clix,
conversionService,
createSqlBuilder,
+ EMPTY_BREAKDOWN_LABEL,
formatClickhouseDate,
funnelService,
getChartPrevStartEndDate,
@@ -852,10 +853,9 @@ export const chartRouter = createTRPCRouter({
});
// Same shape as the chart's `funnel` CTE: windowFunnel is already
- // computed per primary key, so drop level=0 and select distinct
- // profiles. Re-aggregating with max(level)/any(b_0) here would collapse
- // the breakdown column and make the breakdownValues filter pick an
- // arbitrary value for profiles that appear under more than one.
+ // computed per primary key (with breakdowns attributed at the entry
+ // step, so each group carries one deterministic b_N value), so drop
+ // level=0 and select distinct profiles.
query.with('funnel', 'SELECT * FROM session_funnel WHERE level != 0');
query.select(['DISTINCT profile_id']).from('funnel');
@@ -866,11 +866,26 @@ export const chartRouter = createTRPCRouter({
query.where('level', '>=', targetLevel);
}
- // Filter by specific breakdown values when a breakdown row was clicked
+ // Filter by specific breakdown values when a breakdown row was clicked.
+ // The clicked row carries DISPLAY labels — trimmed, with empty/null
+ // shown as EMPTY_BREAKDOWN_LABEL (see toSeries/normalizeBreakdownValue)
+ // — so match against the same normalization, not the raw column, or
+ // "Not set" rows and values with stray whitespace return no users.
+ // toString/ifNull make the comparison safe for numeric breakdown
+ // columns (trim on a number is a type error) and for Nullable ones
+ // (trim(NULL) = '' is NULL, never true).
breakdowns.forEach((_, index) => {
const value = breakdownValues[index];
- if (value !== undefined) {
- query.where(`b_${index}`, '=', value);
+ if (value === undefined) {
+ return;
+ }
+ const normalized = `trim(ifNull(toString(b_${index}), ''))`;
+ if (value === EMPTY_BREAKDOWN_LABEL) {
+ query.rawWhere(
+ `(${normalized} = '' OR ${normalized} = ${sqlstring.escape(EMPTY_BREAKDOWN_LABEL)})`
+ );
+ } else {
+ query.rawWhere(`${normalized} = ${sqlstring.escape(value)}`);
}
});