OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(api): profile search finds profiles created before the list window
Carl-Gerhard Lindesvärd69a0ff79e304
diff --git a/packages/core/src/modules/profile/profile.rpc.ts b/packages/core/src/modules/profile/profile.rpc.tsindex 22f847708..09e483b23 100644--- a/packages/core/src/modules/profile/profile.rpc.ts+++ b/packages/core/src/modules/profile/profile.rpc.ts@@ -25,6 +25,9 @@ const DEFAULT_LIST_TAKE = 50;/** A list page, not an export. `/export/events` is the bulk path. */const MAX_LIST_TAKE = 1000;+/** Longer than any name or email; a search past it is not a lookup. */+const MAX_LIST_SEARCH_LENGTH = 100;+/*** `list` and `powerUsers` need a date window: without one their cost grows with the* tenant's lifetime (44.2 M rows read for one page of 50). This is the default when@@ -134,7 +137,7 @@ export const profileRouter = createTRPCRouter({.min(1).max(MAX_LIST_TAKE).default(DEFAULT_LIST_TAKE),- search: z.string().optional(),+ search: z.string().trim().max(MAX_LIST_SEARCH_LENGTH).optional(),isExternal: z.boolean().optional(),filters: z.array(zChartEventFilter).default([]),...zProfileWindow,diff --git a/packages/core/src/modules/profile/src/sql.test.ts b/packages/core/src/modules/profile/src/sql.test.tsindex c74addda3..8ab89adec 100644--- a/packages/core/src/modules/profile/src/sql.test.ts+++ b/packages/core/src/modules/profile/src/sql.test.ts@@ -194,19 +194,39 @@ describe('profileListQuery', () => {// The raw-row conditions only narrow the id set (a superset); the same// conditions on the newest version decide, in HAVING.expect(text).toContain(- "(SELECT id FROM profiles WHERE project_id = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) AND cityHash64(id) IN (SELECT cityHash64(id) FROM profiles WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND ((id ILIKE {p8:String} OR email ILIKE {p9:String} OR first_name ILIKE {p10:String} OR last_name ILIKE {p11:String} OR concat(first_name, ' ', last_name) ILIKE {p12:String})) AND is_external = {p13:Bool} AND (properties['plan'] = 'pro')) GROUP BY id HAVING ((id ILIKE {p14:String} OR argMax(email, last_seen_at) ILIKE {p15:String} OR argMax(first_name, last_seen_at) ILIKE {p16:String} OR argMax(last_name, last_seen_at) ILIKE {p17:String} OR concat(argMax(first_name, last_seen_at), ' ', argMax(last_name, last_seen_at)) ILIKE {p18:String})) AND argMax(is_external, last_seen_at) = {p19:Bool} AND (argMax(properties['plan'], last_seen_at) = 'pro') ORDER BY argMax(created_at, last_seen_at) DESC LIMIT {p20:UInt64} OFFSET {p21:UInt64})"+ "(SELECT id FROM profiles WHERE project_id = {p2:String} AND cityHash64(id) IN (SELECT cityHash64(id) FROM profiles WHERE project_id = {p3:String} AND ((id ILIKE {p4:String} OR email ILIKE {p5:String} OR first_name ILIKE {p6:String} OR last_name ILIKE {p7:String} OR concat(first_name, ' ', last_name) ILIKE {p8:String})) AND is_external = {p9:Bool} AND (properties['plan'] = 'pro')) GROUP BY id HAVING ((id ILIKE {p10:String} OR argMax(email, last_seen_at) ILIKE {p11:String} OR argMax(first_name, last_seen_at) ILIKE {p12:String} OR argMax(last_name, last_seen_at) ILIKE {p13:String} OR concat(argMax(first_name, last_seen_at), ' ', argMax(last_name, last_seen_at)) ILIKE {p14:String})) AND argMax(is_external, last_seen_at) = {p15:Bool} AND (argMax(properties['plan'], last_seen_at) = 'pro') ORDER BY argMax(created_at, last_seen_at) DESC LIMIT {p16:UInt64} OFFSET {p17:UInt64})");expect(query_params).toMatchObject({p1: PROJECT_ID,- p8: '%ann%',- p13: true,- p14: '%ann%',- p19: true,- p20: 50,- p21: 100,+ p4: '%ann%',+ p9: true,+ p10: '%ann%',+ p15: true,+ p16: 50,+ p17: 100,});});+ test('a search reaches past the window; one shorter than the minimum is ignored', () => {+ const page = (search: string) =>+ collapse(+ profileListQuery({+ projectId: PROJECT_ID,+ take: 50,+ offset: 0,+ search,+ ...NO_FILTER_CLAUSES,+ ...WINDOW,+ }).toStatement().query+ );+ const unsearched = page('');++ expect(page('an')).not.toContain('created_at BETWEEN');+ expect(page('an')).toContain('ILIKE');+ expect(page(' a ')).toBe(unsearched);+ expect(unsearched).toContain('created_at BETWEEN');+ });+test('count counts exactly the ids the page selects from', () => {const list = {projectId: PROJECT_ID,diff --git a/packages/core/src/modules/profile/src/sql.ts b/packages/core/src/modules/profile/src/sql.tsindex 9b4cffa8a..a2fe7564d 100644--- a/packages/core/src/modules/profile/src/sql.ts+++ b/packages/core/src/modules/profile/src/sql.ts@@ -69,6 +69,8 @@ const PROFILE_LATEST_COLUMNS_FRAGMENT = sql.join();const SEARCH_MAX_TOKENS = 5;+/** Below this the list ignores the search: one letter matches nearly every profile. */+export const PROFILE_LIST_SEARCH_MIN_LENGTH = 2;const SEARCH_TOKEN_SEPARATOR = /\s+/;function optional(@@ -276,15 +278,28 @@ function latestProfilesPage(`;}+function profileListSearch(query: ProfileListQuery): string | undefined {+ const search = query.search?.trim();+ return search && search.length >= PROFILE_LIST_SEARCH_MIN_LENGTH+ ? search+ : undefined;+}+/**- * `project_id =.. AND created_at BETWEEN ..`: bounded to a window rather than- * reading every profile the project ever had — otherwise the cost grows with- * the tenant's lifetime rather than with anything the caller asked for.+ * `project_id =.. [AND created_at BETWEEN ..]`: bounded to a window rather+ * than reading every profile the project ever had — otherwise the cost grows+ * with the tenant's lifetime rather than with anything the caller asked for.* `created_at` is the column the list already orders by, so the bound and* the order agree; the write path keeps it the same across versions.+ * A search is the exception: looking someone up by name has to find them+ * however long ago they signed up, and the search itself bounds the rows.*/function profileListScope(query: ProfileListQuery): SqlFragment {- return sql`project_id = ${sql.string(query.projectId)} AND ${dateRangeWhere(+ const projectScope = sql`project_id = ${sql.string(query.projectId)}`;+ if (profileListSearch(query)) {+ return projectScope;+ }+ return sql`${projectScope} AND ${dateRangeWhere('created_at',query.startDate,query.endDate@@ -301,7 +316,7 @@ function profileListConditions(filterClauses: CompiledFilterClauses): SqlFragment[] {const conditions: SqlFragment[] = [];- const search = profileSearchCondition(query.search, column);+ const search = profileSearchCondition(profileListSearch(query), column);if (search) {conditions.push(search);}diff --git a/packages/core/src/modules/profile/src/sql.versions.test.ts b/packages/core/src/modules/profile/src/sql.versions.test.tsindex 916eeb4f1..e7d62b11d 100644--- a/packages/core/src/modules/profile/src/sql.versions.test.ts+++ b/packages/core/src/modules/profile/src/sql.versions.test.ts@@ -233,6 +233,25 @@ describe('profileListQuery / profileListCountQuery', () => {expect(await countOf(count({ isExternal: true }))).toBe(3);expect(await countOf(count({ isExternal: false }))).toBe(0);});++ it('a search finds a profile created before the window, by its newest version', async () => {+ const recentWindow = {+ startDate: timeAgo(now, 15),+ endDate: timeAgo(now, 0),+ };+ expect(ids(await fetchRows(ch, list(recentWindow)))).toEqual([+ VERSIONED.single,+ ]);+ expect(+ ids(await fetchRows(ch, list({ ...recentWindow, search: 'Kim-Lee' })))+ ).toEqual([VERSIONED.multi]);+ expect(await countOf(count({ ...recentWindow, search: 'Kim-Lee' }))).toBe(+ 1+ );+ expect(+ ids(await fetchRows(ch, list({ ...recentWindow, search: 'mia@old' })))+ ).toEqual([]);+ });});describe('findProfilesQuery', () => {