Skip to content

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

fix(analytics): keep sessionless events out of session-grouped funnels, flows and page durations (#601)

I'm Groot 🌳1418e31c9c74
diff --git a/packages/core/src/modules/chart/src/conversion.sql.ts b/packages/core/src/modules/chart/src/conversion.sql.ts
index 3682e390e..32a4fd154 100644
--- a/packages/core/src/modules/chart/src/conversion.sql.ts
+++ b/packages/core/src/modules/chart/src/conversion.sql.ts
@@ -121,6 +121,8 @@ export function conversionQuery(input: ConversionQueryInput): SqlFragment {
cohortJoins,
} = input;
+ const sessionFilter =
+ group === 'session_id' ? sql`AND events.session_id != ''` : sql.empty;
const groupKey = sql.id(group, CONVERSION_GROUPS);
const breakdownAliases = breakdownSelects.map((_, index) =>
compiledText(`b_${index}`)
@@ -166,6 +168,7 @@ export function conversionQuery(input: ConversionQueryInput): SqlFragment {
${groupJoin(needsGroupArrayJoin, projectId)}
${sql.join(cohortJoins, ' ')}
WHERE project_id = ${sql.string(projectId)}
+ ${sessionFilter}
${eventNames.includes('*') ? sql.empty : sql`AND events.name IN ${sql.array('String', eventNames)}`}
AND ${dateRange}
GROUP BY ${groupKey}${innerBreakdownGroupBy})
diff --git a/packages/core/src/modules/chart/src/funnel.sql.ts b/packages/core/src/modules/chart/src/funnel.sql.ts
index 8890f4186..31b61bc3e 100644
--- a/packages/core/src/modules/chart/src/funnel.sql.ts
+++ b/packages/core/src/modules/chart/src/funnel.sql.ts
@@ -342,6 +342,7 @@ function profileJoinFilters(eventSeries: IChartEvent[]): IChartEventFilter[] {
);
}
+/** Empty session IDs cannot define funnels; sessionless profiles remain eligible. */
export function funnelBase(input: FunnelBaseInput): FunnelBase {
const { projectId, eventSeries, breakdowns, group } = input;
@@ -374,6 +375,8 @@ export function funnelBase(input: FunnelBaseInput): FunnelBase {
);
const selects = breakdownSelects(input, profileKeys.keys, conditions);
+ const sessionFilter =
+ group === 'session_id' ? sql` AND events.session_id != ''` : sql.empty;
const primaryKey = sql.id(group, FUNNEL_GROUPS);
const cteSelects: SqlFragment[] = [
primaryKey,
@@ -432,7 +435,7 @@ export function funnelBase(input: FunnelBaseInput): FunnelBase {
' OR '
)})`;
- const funnelCte = sql`SELECT ${sql.join(cteSelects)} FROM ${sql.id(CHART_TABLE.events)}${profileJoin}${groupJoin}${cohortJoins} WHERE project_id = ${sql.string(projectId)} AND ${dateRange}${eventNames.includes('*') ? sql.empty : sql` AND events.name IN ${sql.array('String', eventNames)}`} AND ${stepPreFilter} GROUP BY ${sql.join(groupByKeys)}`;
+ const funnelCte = sql`SELECT ${sql.join(cteSelects)} FROM ${sql.id(CHART_TABLE.events)}${profileJoin}${groupJoin}${cohortJoins} WHERE project_id = ${sql.string(projectId)}${sessionFilter} AND ${dateRange}${eventNames.includes('*') ? sql.empty : sql` AND events.name IN ${sql.array('String', eventNames)}`} AND ${stepPreFilter} GROUP BY ${sql.join(groupByKeys)}`;
const groupsCte = needsGroupArrayJoin
? sql`_g AS (${buildGroupsQuery(projectId)}), `
diff --git a/packages/core/src/modules/chart/src/sankey.sql.ts b/packages/core/src/modules/chart/src/sankey.sql.ts
index c4f85e48b..1d23ba48f 100644
--- a/packages/core/src/modules/chart/src/sankey.sql.ts
+++ b/packages/core/src/modules/chart/src/sankey.sql.ts
@@ -95,7 +95,7 @@ function sessionEventCte(
const filters = event.whereClause
? sql` AND ${event.whereClause}`
: sql.empty;
- return sql`SELECT session_id FROM ${sql.id(CHART_TABLE.events)} WHERE project_id = ${sql.string(input.projectId)} AND name = ${sql.string(event.name)} AND created_at BETWEEN toDateTime(${sql.string(input.startDate)}) AND toDateTime(${sql.string(input.endDate)})${filters} GROUP BY session_id`;
+ return sql`SELECT session_id FROM ${sql.id(CHART_TABLE.events)} WHERE project_id = ${sql.string(input.projectId)} AND session_id != '' AND name = ${sql.string(event.name)} AND created_at BETWEEN toDateTime(${sql.string(input.startDate)}) AND toDateTime(${sql.string(input.endDate)})${filters} GROUP BY session_id`;
}
interface ModeConfig {
@@ -169,7 +169,7 @@ export function sankeySessionPathsQuery(input: SankeyPathsInput): SqlFragment {
const eventsExpr =
input.mode === 'after' ? TRUNCATE_AT_REPEAT : sql`events_sliced`;
- return sql`WITH ${anchors}events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM ${sql.id(CHART_TABLE.events)} WHERE ${dateRange(input)}${eventNameFilter(input)} ORDER BY session_id ASC, created_at ASC) SELECT session_id, ${DEDUPE_CONSECUTIVE} FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, ${eventsSlice} as events_sliced FROM events_deduped_cte HAVING ${having}) SELECT session_id, ${eventsExpr} as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= ${sql.uint64(MIN_PATH_LENGTH)}`;
+ return sql`WITH ${anchors}events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM ${sql.id(CHART_TABLE.events)} WHERE ${dateRange(input)} AND session_id != ''${eventNameFilter(input)} ORDER BY session_id ASC, created_at ASC) SELECT session_id, ${DEDUPE_CONSECUTIVE} FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, ${eventsSlice} as events_sliced FROM events_deduped_cte HAVING ${having}) SELECT session_id, ${eventsExpr} as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= ${sql.uint64(MIN_PATH_LENGTH)}`;
}
/**
diff --git a/packages/core/src/modules/overview/src/overview.sql.ts b/packages/core/src/modules/overview/src/overview.sql.ts
index fcd7c501d..da0f093ae 100644
--- a/packages/core/src/modules/overview/src/overview.sql.ts
+++ b/packages/core/src/modules/overview/src/overview.sql.ts
@@ -187,6 +187,7 @@ function rollupDateLiteral(interval: IInterval): SqlFragment {
: sql`toDateTime(${sql.string(`${ROLLUP_DATE_PREFIX} 00:00:00`)})`;
}
+/** Sessionless views still count, but cannot contribute elapsed time. */
export function metricsWithPageFilterQuery(
input: PageFilterMetricsQueryInput
): SqlFragment {
@@ -209,7 +210,7 @@ export function metricsWithPageFilterQuery(
${dateBucket} AS date,
profile_id,
session_id,
- dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at)) AS duration,
+ if(session_id = '', 0, dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at))) AS duration,
${input.rawEventFilterWhere ?? sql`true`} AS matches_filter
FROM events
WHERE project_id = ${sql.string(input.projectId)}
@@ -556,12 +557,14 @@ export interface OrderedEventsQueryInput {
rawFilterWhere: SqlFragment | null;
}
+/** The empty ID is shared by unrelated events, so it cannot define a journey. */
function orderedEventsQuery(input: OrderedEventsQueryInput): SqlFragment {
return sql`
SELECT session_id, concat(origin, path) as path, created_at
FROM events
WHERE project_id = ${sql.string(input.projectId)}
AND name = 'screen_view'
+ AND session_id != ''
AND path != ''
AND path IS NOT NULL
AND ${dateRangeWhere('created_at', input.startDate, input.endDate)}
diff --git a/packages/core/src/modules/overview/src/pages.sql.ts b/packages/core/src/modules/overview/src/pages.sql.ts
index aa4698b85..6527c0966 100644
--- a/packages/core/src/modules/overview/src/pages.sql.ts
+++ b/packages/core/src/modules/overview/src/pages.sql.ts
@@ -47,6 +47,7 @@ function searchClause(search: string | undefined): SqlFragment {
return sql`AND (e.path LIKE ${term} OR e.origin LIKE ${term} OR pt.title LIKE ${term})`;
}
+/** Sessionless views still count, but cannot contribute elapsed time. */
export function topPagesQuery(input: TopPagesQueryInput): SqlFragment {
// Titles come from the requested range so the answer does not depend on the
// wall clock — reading a fixed lookback window off the widest Map column
@@ -67,7 +68,7 @@ export function topPagesQuery(input: TopPagesQueryInput): SqlFragment {
session_id,
path,
origin,
- dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at)) AS duration
+ if(session_id = '', 0, dateDiff('millisecond', created_at, lead(created_at, 1, created_at) OVER (PARTITION BY session_id ORDER BY created_at))) AS duration
FROM events
WHERE project_id = ${sql.string(input.projectId)}
AND name = 'screen_view'
diff --git a/packages/core/test/sessionless-analytics.test.ts b/packages/core/test/sessionless-analytics.test.ts
new file mode 100644
index 000000000..4d57da2ea
--- /dev/null
+++ b/packages/core/test/sessionless-analytics.test.ts
@@ -0,0 +1,282 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { createClient } from '@openpanel/db/src/clickhouse/client';
+import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';
+import {
+ clickhouseUrl,
+ TEST_CLICKHOUSE_DATABASE,
+ TEST_CLICKHOUSE_URL,
+} from '../../../test/databases';
+import { conversionQuery } from '../src/modules/chart/src/conversion.sql';
+import {
+ funnelBase,
+ funnelChartQuery,
+} from '../src/modules/chart/src/funnel.sql';
+import { sankeySessionPathsQuery } from '../src/modules/chart/src/sankey.sql';
+import {
+ metricsWithPageFilterQuery,
+ topEntriesQuery,
+ transitionsQuery,
+} from '../src/modules/overview/src/overview.sql';
+import { topPagesQuery } from '../src/modules/overview/src/pages.sql';
+
+const database = `${TEST_CLICKHOUSE_DATABASE}_sessionless_${crypto.randomUUID().replaceAll('-', '')}`;
+const admin = createClient({ url: TEST_CLICKHOUSE_URL });
+const ch = createClient({ url: clickhouseUrl(database) });
+const window = {
+ projectId: 'sessionless-regression',
+ startDate: '2026-08-01 00:00:00',
+ endDate: '2026-08-01 23:59:59',
+};
+const ORIGIN = 'https://example.com';
+
+/** Separate profiles deliberately share only the empty session sentinel. */
+function event(
+ name: string,
+ session: string,
+ profile: string,
+ seconds: number,
+ path = ''
+) {
+ return {
+ project_id: window.projectId,
+ name,
+ session_id: session,
+ profile_id: profile,
+ created_at: new Date(Date.UTC(2026, 7, 1) + seconds * 1000)
+ .toISOString()
+ .replace('T', ' ')
+ .replace('Z', ''),
+ origin: ORIGIN,
+ path,
+ properties: {},
+ groups: [],
+ };
+}
+
+beforeAll(async () => {
+ await admin.command({
+ query: 'CREATE DATABASE {database:Identifier}',
+ query_params: { database },
+ });
+ await ch.command({
+ query: `CREATE TABLE events (
+ project_id String, name String, session_id String, profile_id String,
+ created_at DateTime64(3, 'UTC'), origin String, path String,
+ properties Map(String, String), groups Array(String)
+ ) ENGINE = Memory`,
+ });
+ await ch.command({
+ query: `CREATE TABLE sessions (
+ id String, project_id String, created_at DateTime64(3, 'UTC'),
+ is_bounce Bool, sign Int8, version UInt64
+ ) ENGINE = VersionedCollapsingMergeTree(sign, version) ORDER BY (project_id, id)`,
+ });
+ await ch.insert({
+ table: 'events',
+ format: 'JSONEachRow',
+ values: [
+ event('begin', 'browser-1', 'visitor-1', 0),
+ event('screen_view', 'browser-1', 'visitor-1', 1, '/entry'),
+ event('screen_view', 'browser-1', 'visitor-1', 61, '/next'),
+ event('finish', 'browser-1', 'visitor-1', 120),
+ event('begin', 'browser-2', 'visitor-2', 30),
+ event('screen_view', 'browser-2', 'visitor-2', 31, '/lonely'),
+ event('begin', '', 'server-a', 10),
+ event('screen_view', '', 'server-a', 11, '/fake-entry'),
+ event('finish', '', 'server-b', 20),
+ event('screen_view', '', 'server-b', 191, '/fake-next'),
+ event('begin', '', 'server-c', 240),
+ event('finish', '', 'server-c', 250),
+ ],
+ });
+});
+
+afterAll(async () => {
+ await ch.close();
+ await admin.command({
+ query: 'DROP DATABASE IF EXISTS {database:Identifier}',
+ query_params: { database },
+ });
+ await admin.close();
+});
+
+/** Execute the actual builders with bound parameters rather than matching SQL text. */
+async function rows(fragment: SqlFragment): Promise<Record<string, unknown>[]> {
+ const result = await ch.query({
+ ...fragment.toStatement(),
+ format: 'JSONEachRow',
+ clickhouse_settings: {
+ session_timezone: 'UTC',
+ output_format_json_quote_64bit_integers: 0,
+ },
+ });
+ return result.json<Record<string, unknown>>();
+}
+
+test.each([
+ 'session_id',
+ 'profile_id',
+] as const)('funnel grouped by %s does not merge unrelated profiles', async (group) => {
+ const result = await rows(
+ funnelChartQuery(
+ funnelBase({
+ ...window,
+ group,
+ timezone: 'UTC',
+ breakdowns: [],
+ cohortMetadata: new Map(),
+ funnelWindowMilliseconds: 3_600_000,
+ eventSeries: ['begin', 'finish'].map((name, index) => ({
+ id: String(index),
+ type: 'event',
+ name,
+ segment: 'event',
+ filters: [],
+ })),
+ })
+ )
+ );
+ const count = group === 'session_id' ? 1 : 2;
+ expect(result).toEqual([
+ { level: 2, count },
+ { level: 1, count },
+ ]);
+});
+
+test.each([
+ 'session_id',
+ 'profile_id',
+] as const)('conversion grouped by %s retains the intended grouping', async (group) => {
+ const result = await rows(
+ conversionQuery({
+ ...window,
+ group,
+ interval: 'day',
+ funnelWindowSeconds: 3600,
+ firstEventMatch: sql`name = 'begin'`,
+ secondEventMatch: sql`name = 'finish'`,
+ eventNames: ['begin', 'finish'],
+ firstEventWhere: null,
+ secondEventWhere: null,
+ breakdownSelects: [],
+ breakdownExpressions: [],
+ profileJoinFields: [],
+ needsGroupArrayJoin: false,
+ cohortJoins: [],
+ })
+ );
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ total_first: group === 'session_id' ? 2 : 4,
+ conversions: group === 'session_id' ? 1 : 2,
+ conversion_rate_percentage: 50,
+ });
+});
+
+test.each([
+ 'after',
+ 'before',
+ 'between',
+] as const)('flow %s excludes sessionless paths', async (mode) => {
+ const result = await rows(
+ sankeySessionPathsQuery({
+ ...window,
+ mode,
+ steps: 8,
+ exclude: [],
+ startEvent: {
+ name: mode === 'before' ? 'finish' : 'begin',
+ whereClause: null,
+ },
+ ...(mode === 'between'
+ ? { endEvent: { name: 'finish', whereClause: null } }
+ : {}),
+ })
+ );
+ expect(result.map((row) => row.session_id).sort()).toEqual(
+ mode === 'after' ? ['browser-1', 'browser-2'] : ['browser-1']
+ );
+});
+
+test('user journey entries exclude sessionless paths', async () => {
+ const input = { ...window, steps: 8, rawFilterWhere: null };
+ expect(await rows(topEntriesQuery({ ...input, topEntries: 10 }))).toEqual([
+ { entry_page: `${ORIGIN}/entry`, count: 1 },
+ ]);
+});
+
+test('user journey transitions do not stitch server profiles together', async () => {
+ const input = { ...window, steps: 8, rawFilterWhere: null };
+ expect(
+ await rows(
+ transitionsQuery({
+ ...input,
+ topEntryPages: [`${ORIGIN}/entry`, `${ORIGIN}/fake-entry`],
+ })
+ )
+ ).toEqual([
+ { source: `${ORIGIN}/entry`, target: `${ORIGIN}/next`, step: 1, value: 1 },
+ ]);
+});
+
+test('pages retain sessionless pageviews but give them zero duration', async () => {
+ const result = await rows(topPagesQuery(window));
+ expect(result.reduce((sum, row) => sum + Number(row.pageviews), 0)).toBe(5);
+ expect(result).toHaveLength(5);
+ expect(result.find((row) => row.path === '/entry')).toMatchObject({
+ pageviews: 1,
+ avg_duration: 1,
+ });
+ for (const path of ['/fake-entry', '/fake-next', '/lonely', '/next']) {
+ expect(result.find((row) => row.path === path)).toMatchObject({
+ pageviews: 1,
+ avg_duration: 0,
+ });
+ }
+});
+
+test.each([
+ { paths: ['/entry', '/fake-entry'], views: 2, visitors: 2, duration: 60 },
+ { paths: ['/fake-entry', '/fake-next'], views: 2, visitors: 2, duration: 0 },
+])('page-filtered metrics retain views and visitors: %j', async ({
+ paths,
+ views,
+ visitors,
+ duration,
+}) => {
+ const result = await rows(
+ metricsWithPageFilterQuery({
+ ...window,
+ interval: 'day',
+ rawSessionFilterWhere: null,
+ rawEventFilterWhere: sql`path IN ${sql.array('String', paths)}`,
+ })
+ );
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ total_screen_views: views,
+ unique_visitors: visitors,
+ avg_session_duration: duration,
+ });
+});
+
+test('a flood of sessionless views does not become one large user journey', async () => {
+ const projectId = `${window.projectId}-bulk`;
+ await ch.command({
+ query: `INSERT INTO events SELECT {project:String}, 'screen_view', '', concat('server-', toString(number)),
+ toDateTime64('2026-08-01 01:00:00', 3, 'UTC') + toIntervalMillisecond(number),
+ {origin:String}, concat('/bulk/', toString(number)), map(), [] FROM numbers(100000)`,
+ query_params: { project: projectId, origin: ORIGIN },
+ });
+ expect(
+ await rows(
+ topEntriesQuery({
+ ...window,
+ projectId,
+ steps: 8,
+ rawFilterWhere: null,
+ topEntries: 10,
+ })
+ )
+ ).toEqual([]);
+});