OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
perf(api): profile lookups read the newest row instead of profiles FINAL
Carl-Gerhard Lindesvärdf9e675357171
diff --git a/packages/core/src/modules/profile/src/sql.test.ts b/packages/core/src/modules/profile/src/sql.test.tsindex c4caf63ca..d03363e5a 100644--- a/packages/core/src/modules/profile/src/sql.test.ts+++ b/packages/core/src/modules/profile/src/sql.test.ts@@ -89,25 +89,26 @@ describe('single-profile lookups', () => {}).toStatement();expect(collapse(byId.query)).toBe(- `SELECT ${COLUMN_LIST} FROM profiles FINAL WHERE id = {p1:String} AND project_id = {p2:String} LIMIT 1`+ `SELECT ${COLUMN_LIST} FROM profiles WHERE id = {p1:String} AND project_id = {p2:String} ORDER BY last_seen_at DESC LIMIT 1`);expect(byId.query_params).toEqual({ p1: HOSTILE, p2: PROJECT_ID });expect(collapse(row.query)).toBe(- `SELECT ${COLUMN_LIST} FROM profiles FINAL WHERE project_id = {p1:String} AND id = {p2:String} LIMIT 1`+ `SELECT ${COLUMN_LIST} FROM profiles WHERE project_id = {p1:String} AND id = {p2:String} ORDER BY last_seen_at DESC LIMIT 1`);expect(row.query_params).toEqual({ p1: PROJECT_ID, p2: HOSTILE });});- test('profilesByIdsQuery filters by sort key in PREWHERE, binding ids as one Array(String)', () => {+ test('profilesByIdsQuery picks the newest version per id, binding ids as one Array(String)', () => {const { query, query_params } = profilesByIdsQuery({projectId: PROJECT_ID,ids: ['a', HOSTILE],}).toStatement();expect(collapse(query)).toContain(- 'FROM profiles FINAL PREWHERE project_id = {p1:String} AND id IN {p2:Array(String)}'+ 'FROM profiles AS p WHERE p.project_id = {p1:String} AND p.id IN {p2:Array(String)} GROUP BY p.id, p.project_id');- expect(query).not.toMatch(PLAIN_WHERE);+ expect(query).toContain('argMax(properties, p.last_seen_at) AS properties');+ expect(query).not.toContain('FINAL');expect(query).not.toContain(HOSTILE);expect(query_params).toEqual({ p1: PROJECT_ID, p2: ['a', HOSTILE] });});diff --git a/packages/core/src/modules/profile/src/sql.ts b/packages/core/src/modules/profile/src/sql.tsindex b96a93880..fd14d79ac 100644--- a/packages/core/src/modules/profile/src/sql.ts+++ b/packages/core/src/modules/profile/src/sql.ts@@ -35,6 +35,27 @@ const PROFILE_COLUMNS_FRAGMENT = sql.join(', ');+const PROFILE_KEY_COLUMNS = ['id', 'project_id'] as const;++/**+ * The newest version of every column, as `profiles FINAL` would return it,+ * for a `GROUP BY id, project_id` over the raw rows. `last_seen_at` is the+ * ReplacingMergeTree version column; the `p.` prefix keeps it from resolving+ * to the aggregate alias of the same name.+ */+const PROFILE_LATEST_COLUMNS_FRAGMENT = sql.join(+ PROFILE_COLUMNS.map((column) => {+ if ((PROFILE_KEY_COLUMNS as readonly string[]).includes(column)) {+ return sql.id(column, PROFILE_COLUMNS);+ }+ if (column === 'last_seen_at') {+ return sql`max(p.last_seen_at) AS last_seen_at`;+ }+ return sql`argMax(${sql.id(column, PROFILE_COLUMNS)}, p.last_seen_at) AS ${sql.id(column, PROFILE_COLUMNS)}`;+ }),+ ', '+);+const SEARCH_MAX_TOKENS = 5;const SEARCH_TOKEN_SEPARATOR = /\s+/;@@ -93,14 +114,15 @@ export function profileMetricsQuery(query: {}): SqlFragment {const profileId = sql.string(query.profileId);const projectId = sql.string(query.projectId);- // FINAL turns off automatic PREWHERE. Both PREWHERE columns are in the sort- // key, so a -1 and its +1 pass together; `sign` stays in WHERE so the- // collapse happens first.+ // FINAL turns off automatic PREWHERE on `sessions`. Both PREWHERE columns+ // are in the sort key, so a -1 and its +1 pass together; `sign` stays in+ // WHERE so the collapse happens first.return sql`WITH profileSeen AS (SELECT created_at as firstSeen, last_seen_at as lastSeen- FROM ${sql.id(TABLE.profiles)} FINAL+ FROM ${sql.id(TABLE.profiles)}WHERE id = ${profileId} AND project_id = ${projectId}+ ORDER BY last_seen_at DESCLIMIT 1),eventStats AS (@@ -150,8 +172,9 @@ export function profileByIdQuery(query: {}): SqlFragment {return sql`SELECT ${PROFILE_COLUMNS_FRAGMENT}- FROM ${sql.id(TABLE.profiles)} FINAL+ FROM ${sql.id(TABLE.profiles)}WHERE id = ${sql.string(query.id)} AND project_id = ${sql.string(query.projectId)}+ ORDER BY last_seen_at DESCLIMIT 1`;}@@ -160,15 +183,13 @@ export function profilesByIdsQuery(query: {projectId: string;ids: readonly string[];}): SqlFragment {- // FINAL turns off automatic PREWHERE, so without it every column (mostly- // `properties`) is read for the whole project range. Safe before the FINAL- // merge: both conditions are sort-key columns, shared by every row version.return sql`- SELECT ${PROFILE_COLUMNS_FRAGMENT}- FROM ${sql.id(TABLE.profiles)} FINAL- PREWHERE- project_id = ${sql.string(query.projectId)} AND- id IN ${sql.array('String', query.ids)}+ SELECT ${PROFILE_LATEST_COLUMNS_FRAGMENT}+ FROM ${sql.id(TABLE.profiles)} AS p+ WHERE+ p.project_id = ${sql.string(query.projectId)} AND+ p.id IN ${sql.array('String', query.ids)}+ GROUP BY p.id, p.project_id`;}@@ -320,8 +341,9 @@ export function profileRowQuery(query: {}): SqlFragment {return sql`SELECT ${PROFILE_COLUMNS_FRAGMENT}- FROM ${sql.id(TABLE.profiles)} FINAL+ FROM ${sql.id(TABLE.profiles)}WHERE project_id = ${sql.string(query.projectId)} AND id = ${sql.string(query.profileId)}+ ORDER BY last_seen_at DESCLIMIT 1`;}diff --git a/packages/core/src/modules/profile/src/sql.versions.test.ts b/packages/core/src/modules/profile/src/sql.versions.test.tsnew file mode 100644index 000000000..3e7c49b42--- /dev/null+++ b/packages/core/src/modules/profile/src/sql.versions.test.ts@@ -0,0 +1,143 @@+// The profile lookups no longer read `profiles FINAL`. Each test runs the+// statement that was replaced (kept verbatim here) and the one the module+// builds now against profiles with several unmerged versions, and the rows+// must match.++import { afterAll, beforeAll, describe, expect, it } from 'bun:test';+import { sql } from '@openpanel/db/src/clickhouse/sql';+import {+ otherProjectId,+ setupProfileVersions,+ teardownProfileVersions,+ VERSIONED,+} from '../../../../../../test/profile-versions';+import { expectSameRows, fetchRows } from '../../../../test/clickhouse-rows';+import {+ PROFILE_COLUMNS,+ profileByIdQuery,+ profileMetricsQuery,+ profileRowQuery,+ profilesByIdsQuery,+} from './sql';++const PROJECT_ID = 'profile-versions-lookups';+const columns = sql.join(+ PROFILE_COLUMNS.map((column) => sql.id(column, PROFILE_COLUMNS)),+ ', '+);++let ch: typeof import('@openpanel/db/src/clickhouse/client').ch;++beforeAll(async () => {+ ({ ch } = await import('@openpanel/db/src/clickhouse/client'));+ const { bootstrapTestDatabases } = await import(+ '../../../../../../test/bootstrap-databases'+ );+ await bootstrapTestDatabases();+ await setupProfileVersions(PROJECT_ID);+}, 30_000);++afterAll(() => teardownProfileVersions(PROJECT_ID));++it('the fixture holds every version unmerged', async () => {+ const [row] = await fetchRows(+ ch,+ sql`SELECT count() AS rows, uniqExact(id) AS ids FROM profiles WHERE project_id = ${sql.string(PROJECT_ID)}`+ );+ const counts = JSON.parse(row as string);+ expect([Number(counts.rows), Number(counts.ids)]).toEqual([6, 3]);+});++function finalById(id: string, projectId = PROJECT_ID) {+ return sql`SELECT ${columns} FROM profiles FINAL WHERE id = ${sql.string(id)} AND project_id = ${sql.string(projectId)} LIMIT 1`;+}++describe('profileByIdQuery / profileRowQuery', () => {+ it.each([+ ['multi-version', VERSIONED.multi, '[email protected]', 'team'],+ ['stale old version', VERSIONED.staleMatch, '[email protected]', 'free'],+ ['single version', VERSIONED.single, '[email protected]', 'pro'],+ ])('%s: returns the latest version', async (_label, id, email, plan) => {+ const [row] = await expectSameRows(+ ch,+ finalById(id),+ profileByIdQuery({ id, projectId: PROJECT_ID }),+ 1+ );+ const parsed = JSON.parse(row as string);+ expect(parsed.email).toBe(email);+ expect(parsed.properties.plan).toBe(plan);++ await expectSameRows(+ ch,+ finalById(id),+ profileRowQuery({ profileId: id, projectId: PROJECT_ID }),+ 1+ );+ });++ it('carries every changed column of the latest version', async () => {+ const [row] = await fetchRows(+ ch,+ profileByIdQuery({ id: VERSIONED.multi, projectId: PROJECT_ID })+ );+ expect(JSON.parse(row as string)).toMatchObject({+ last_name: 'Kim-Lee',+ is_external: true,+ properties: { plan: 'team', country: 'SE', tier: 'gold' },+ groups: [VERSIONED.groups.g1, VERSIONED.groups.g2],+ });+ });++ it('keeps projects apart and misses cleanly', async () => {+ const other = otherProjectId(PROJECT_ID);+ const [row] = await expectSameRows(+ ch,+ finalById(VERSIONED.multi, other),+ profileByIdQuery({ id: VERSIONED.multi, projectId: other }),+ 1+ );+ expect(JSON.parse(row as string).properties.plan).toBe('enterprise');++ await expectSameRows(+ ch,+ finalById('pv-missing'),+ profileByIdQuery({ id: 'pv-missing', projectId: PROJECT_ID }),+ 0+ );+ });+});++describe('profilesByIdsQuery', () => {+ it('returns one latest row per id, only from this project', async () => {+ const ids = [+ VERSIONED.multi,+ VERSIONED.staleMatch,+ VERSIONED.single,+ 'pv-missing',+ ];+ const rows = await expectSameRows(+ ch,+ sql`SELECT ${columns} FROM profiles FINAL PREWHERE project_id = ${sql.string(PROJECT_ID)} AND id IN ${sql.array('String', ids)}`,+ profilesByIdsQuery({ projectId: PROJECT_ID, ids }),+ 3+ );+ const plans = rows.map((row) => JSON.parse(row).properties.plan).sort();+ expect(plans).toEqual(['free', 'pro', 'team']);+ });+});++describe('profileMetricsQuery', () => {+ it('reads first/last seen from the latest version', async () => {+ const [metrics] = await fetchRows(+ ch,+ profileMetricsQuery({ profileId: VERSIONED.multi, projectId: PROJECT_ID })+ );+ const [seen] = await fetchRows(+ ch,+ sql`SELECT created_at as firstSeen, last_seen_at as lastSeen FROM profiles FINAL WHERE id = ${sql.string(VERSIONED.multi)} AND project_id = ${sql.string(PROJECT_ID)} LIMIT 1`+ );+ const expected = JSON.parse(seen as string);+ expect(JSON.parse(metrics as string)).toMatchObject(expected);+ });+});diff --git a/packages/core/test/clickhouse-rows.ts b/packages/core/test/clickhouse-rows.tsnew file mode 100644index 000000000..3059831e0--- /dev/null+++ b/packages/core/test/clickhouse-rows.ts@@ -0,0 +1,52 @@+// Row-level equivalence for a query rewrite: both statements run against the+// test ClickHouse and must produce the same rows, order ignored.++import { expect } from 'bun:test';+import type { ch as ChClient } from '@openpanel/db/src/clickhouse/client';+import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';++type Ch = typeof ChClient;++function stableRow(row: Record<string, unknown>): string {+ return JSON.stringify(+ Object.fromEntries(+ Object.entries(row).sort(([left], [right]) => left.localeCompare(right))+ )+ );+}++/** Every row as a canonical string, sorted, so two result sets compare as sets. */+export async function fetchRows(+ ch: Ch,+ fragment: SqlFragment+): Promise<string[]> {+ const { query, query_params } = fragment.toStatement();+ const result = await ch.query({+ query,+ query_params,+ format: 'JSONEachRow',+ clickhouse_settings: { session_timezone: 'UTC' },+ });+ const rows = (await result.json()) as Record<string, unknown>[];+ return rows.map(stableRow).sort();+}++/**+ * `reference` is the statement being replaced (with `FINAL`), written out in+ * the test so it cannot drift with the code; `candidate` is what the module+ * builds now. `expectedCount` guards against both returning nothing.+ */+export async function expectSameRows(+ ch: Ch,+ reference: SqlFragment,+ candidate: SqlFragment,+ expectedCount: number+): Promise<string[]> {+ const [expected, actual] = await Promise.all([+ fetchRows(ch, reference),+ fetchRows(ch, candidate),+ ]);+ expect(expected).toHaveLength(expectedCount);+ expect(actual).toEqual(expected);+ return actual;+}diff --git a/test/fixtures.ts b/test/fixtures.tsindex 52773f73f..48312a5da 100644--- a/test/fixtures.ts+++ b/test/fixtures.ts@@ -67,7 +67,7 @@ function getClient() {return createClient({ url });}-function timeAgo(now: Date, days: number, minutesOffset = 0) {+export function timeAgo(now: Date, days: number, minutesOffset = 0) {return (new Date(now.getTime() - days * 86_400_000 - minutesOffset * 60_000).toISOString()@@ -77,7 +77,7 @@ function timeAgo(now: Date, days: number, minutesOffset = 0) {);}-function buildEvent(+export function buildEvent(now: Date,projectId: string,id: string,diff --git a/test/profile-versions.ts b/test/profile-versions.tsnew file mode 100644index 000000000..908d62dde--- /dev/null+++ b/test/profile-versions.ts@@ -0,0 +1,201 @@+/**+ * Profiles with several unmerged versions, for proving a query without+ * `FINAL` returns what `FINAL` would. Every version is its own insert, so its+ * own part, and merges are stopped on `profiles` while the fixture is live;+ * otherwise ClickHouse may collapse the versions before the test runs and the+ * comparison proves nothing. Deletes happen while merges run: a lightweight+ * DELETE is a mutation, and the mutation pool waits on the same stop.+ *+ * multi — 3 versions, inserted out of order (v1, v3, v2): name, email,+ * properties, groups and is_external all change between them+ * staleMatch — an old version with plan=pro, the latest plan=free: a filter+ * on raw rows matches it, a filter on the latest row must not+ * single — one version+ * multi (again) in `<projectId>-other` with its own properties: must not leak+ *+ * Each profile has events in the last 7 days so join shapes have rows to join.+ */++import { createClient } from '../packages/db/src/clickhouse/client';+import { TEST_CLICKHOUSE_URL } from './databases';+import { buildEvent, timeAgo } from './fixtures';++export const VERSIONED = {+ multi: 'pv-multi',+ staleMatch: 'pv-stale-match',+ single: 'pv-single',+ groups: { g1: 'pv-group-1', g2: 'pv-group-2' },+} as const;++export const otherProjectId = (projectId: string) => `${projectId}-other`;++type Version = Record<string, unknown>;++function profileVersions(projectId: string, now: Date): Version[][] {+ const base = (id: string, createdDaysAgo: number) => ({+ id,+ project_id: projectId,+ avatar: '',+ created_at: timeAgo(now, createdDaysAgo),+ });+ return [+ [+ {+ ...base(VERSIONED.multi, 40),+ first_name: 'Mia',+ last_name: 'Kim',+ email: '[email protected]',+ is_external: false,+ properties: { plan: 'free', country: 'US' },+ groups: [],+ last_seen_at: timeAgo(now, 40),+ },+ {+ ...base(VERSIONED.multi, 40),+ first_name: 'Mia',+ last_name: 'Kim-Lee',+ email: '[email protected]',+ is_external: true,+ properties: { plan: 'team', country: 'SE', tier: 'gold' },+ groups: [VERSIONED.groups.g1, VERSIONED.groups.g2],+ last_seen_at: timeAgo(now, 2),+ },+ {+ ...base(VERSIONED.multi, 40),+ first_name: 'Mia',+ last_name: 'Kim',+ email: '[email protected]',+ is_external: true,+ properties: { plan: 'pro', country: 'SE' },+ groups: [VERSIONED.groups.g1],+ last_seen_at: timeAgo(now, 20),+ },+ ],+ [+ {+ ...base(VERSIONED.staleMatch, 30),+ first_name: 'Sam',+ last_name: 'Old',+ email: '[email protected]',+ is_external: true,+ properties: { plan: 'pro', country: 'US' },+ groups: [],+ last_seen_at: timeAgo(now, 30),+ },+ {+ ...base(VERSIONED.staleMatch, 30),+ first_name: 'Sam',+ last_name: 'New',+ email: '[email protected]',+ is_external: true,+ properties: { plan: 'free', country: 'US' },+ groups: [VERSIONED.groups.g1],+ last_seen_at: timeAgo(now, 3),+ },+ ],+ [+ {+ ...base(VERSIONED.single, 10),+ first_name: 'Uno',+ last_name: 'Solo',+ email: '[email protected]',+ is_external: true,+ properties: { plan: 'pro', country: 'DE' },+ groups: [VERSIONED.groups.g2],+ last_seen_at: timeAgo(now, 10),+ },+ ],+ [+ {+ ...base(VERSIONED.multi, 5),+ project_id: otherProjectId(projectId),+ first_name: 'Other',+ last_name: 'Project',+ email: '[email protected]',+ is_external: true,+ properties: { plan: 'enterprise', country: 'NO' },+ groups: [VERSIONED.groups.g1],+ last_seen_at: timeAgo(now, 1),+ },+ ],+ ];+}++function eventRows(projectId: string, now: Date) {+ const event = (+ id: number,+ name: string,+ profileId: string,+ daysBack: number,+ project = projectId+ ) =>+ buildEvent(+ now,+ project,+ `00000000-0000-0000-0000-0000000000${String(id).padStart(2, '0')}`,+ name,+ profileId,+ `sess-${profileId}-${id}`,+ daysBack+ );+ return [+ event(11, 'screen_view', VERSIONED.multi, 6),+ event(12, 'screen_view', VERSIONED.multi, 3),+ event(13, 'screen_view', VERSIONED.multi, 1),+ event(14, 'signup', VERSIONED.multi, 1),+ event(15, 'screen_view', VERSIONED.staleMatch, 4),+ event(16, 'screen_view', VERSIONED.single, 5),+ event(17, 'signup', VERSIONED.single, 5),+ event(18, 'screen_view', VERSIONED.multi, 1, otherProjectId(projectId)),+ ];+}++async function deleteRows(+ client: ReturnType<typeof createClient>,+ projectId: string+) {+ for (const project of [projectId, otherProjectId(projectId)]) {+ await client.command({+ query: `DELETE FROM profiles WHERE project_id = '${project}'`,+ });+ await client.command({+ query: `DELETE FROM events WHERE project_id = '${project}'`,+ });+ }+}++export async function setupProfileVersions(projectId: string): Promise<Date> {+ const client = createClient({ url: TEST_CLICKHOUSE_URL });+ const now = new Date();+ try {+ await deleteRows(client, projectId);+ await client.command({ query: 'SYSTEM STOP MERGES profiles' });+ for (const versions of profileVersions(projectId, now)) {+ for (const version of versions) {+ await client.insert({+ table: 'profiles',+ values: [version],+ format: 'JSONEachRow',+ });+ }+ }+ await client.insert({+ table: 'events',+ values: eventRows(projectId, now),+ format: 'JSONEachRow',+ });+ } finally {+ await client.close();+ }+ return now;+}++export async function teardownProfileVersions(projectId: string) {+ const client = createClient({ url: TEST_CLICKHOUSE_URL });+ try {+ await client.command({ query: 'SYSTEM START MERGES profiles' });+ await deleteRows(client, projectId);+ } finally {+ await client.close();+ }+}