-
Notifications
You must be signed in to change notification settings - Fork 210
perf(rpc): batch goals bulkAnalytics ClickHouse queries for unfiltered goals #680
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
FindMalek
wants to merge
2
commits into
databuddy-analytics:staging
Choose a base branch
from
FindMalek:fix/goals-bulk-analytics-n-plus-1
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { describe, expect, mock, test } from "bun:test"; | ||
|
|
||
| const chQueryMock = mock((_query: string, _params?: Record<string, unknown>) => | ||
| Promise.resolve([] as unknown[]) | ||
| ); | ||
|
|
||
| mock.module("@databuddy/db/clickhouse", () => ({ | ||
| chQuery: chQueryMock, | ||
| chCommand: mock(async () => undefined), | ||
| })); | ||
|
|
||
| const { buildGoalAnalyticsResult, processGoalsConversionCountsBatch } = | ||
| await import("./analytics-utils"); | ||
|
|
||
| describe("processGoalsConversionCountsBatch", () => { | ||
| test("returns an empty map and issues no query for an empty step list", async () => { | ||
| chQueryMock.mockClear(); | ||
|
|
||
| const result = await processGoalsConversionCountsBatch([], { | ||
| websiteId: "site_1", | ||
| startDate: "2026-01-01", | ||
| endDate: "2026-01-07 23:59:59", | ||
| }); | ||
|
|
||
| expect(result.size).toBe(0); | ||
| expect(chQueryMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test("counts every goal in a single ClickHouse round trip", async () => { | ||
| chQueryMock.mockClear(); | ||
| chQueryMock.mockImplementationOnce(() => | ||
| Promise.resolve([ | ||
| { step_num: 1, completions: 42 }, | ||
| { step_num: 2, completions: 7 }, | ||
| { step_num: 3, completions: 0 }, | ||
| ]) | ||
| ); | ||
|
|
||
| const result = await processGoalsConversionCountsBatch( | ||
| [ | ||
| { step_number: 1, type: "PAGE_VIEW", target: "/pricing", name: "Pricing" }, | ||
| { step_number: 2, type: "EVENT", target: "signup", name: "Signup" }, | ||
| { step_number: 3, type: "EVENT", target: "purchase", name: "Purchase" }, | ||
| ], | ||
| { | ||
| websiteId: "site_1", | ||
| startDate: "2026-01-01", | ||
| endDate: "2026-01-07 23:59:59", | ||
| } | ||
| ); | ||
|
|
||
| expect(chQueryMock).toHaveBeenCalledTimes(1); | ||
| expect(result.get(1)).toBe(42); | ||
| expect(result.get(2)).toBe(7); | ||
| expect(result.get(3)).toBe(0); | ||
| }); | ||
|
|
||
| test("never receives a non-empty filter list, which would make batching unsafe", async () => { | ||
| chQueryMock.mockClear(); | ||
| chQueryMock.mockImplementationOnce(() => Promise.resolve([])); | ||
|
|
||
| await processGoalsConversionCountsBatch( | ||
| [{ step_number: 1, type: "EVENT", target: "signup", name: "Signup" }], | ||
| { websiteId: "site_1", startDate: "2026-01-01", endDate: "2026-01-07" } | ||
| ); | ||
|
|
||
| const [query] = chQueryMock.mock.calls.at(-1) as [string]; | ||
| expect(query).not.toContain("browserFilter"); | ||
| expect(query).not.toContain("customFilter"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("buildGoalAnalyticsResult", () => { | ||
| test("computes conversion rate from completions and total entered users", () => { | ||
| const analytics = buildGoalAnalyticsResult("Signup", 25, 100); | ||
|
|
||
| expect(analytics.total_users_completed).toBe(25); | ||
| expect(analytics.total_users_entered).toBe(100); | ||
| expect(analytics.overall_conversion_rate).toBe(25); | ||
| expect(analytics.steps_analytics).toHaveLength(1); | ||
| expect(analytics.steps_analytics[0]?.step_name).toBe("Signup"); | ||
| }); | ||
|
|
||
| test("reports a zero conversion rate instead of dividing by zero", () => { | ||
| const analytics = buildGoalAnalyticsResult("Signup", 0, 0); | ||
|
|
||
| expect(analytics.overall_conversion_rate).toBe(0); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
103 changes: 103 additions & 0 deletions
103
packages/rpc/src/lib/goals-bulk-analytics-grouping.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| import { describe, expect, test } from "bun:test"; | ||
| import { groupGoalsForBulkAnalytics } from "./goals-bulk-analytics-grouping"; | ||
|
|
||
| interface TestFilter { | ||
| field: string; | ||
| operator: string; | ||
| value: string; | ||
| } | ||
|
|
||
| interface TestGoal { | ||
| createdAt: Date | null; | ||
| filters: TestFilter[] | null; | ||
| id: string; | ||
| ignoreHistoricData: boolean; | ||
| } | ||
|
|
||
| const goal = (id: string, filters: TestFilter[] | null = null): TestGoal => ({ | ||
| id, | ||
| createdAt: null, | ||
| ignoreHistoricData: false, | ||
| filters, | ||
| }); | ||
|
|
||
| describe("groupGoalsForBulkAnalytics", () => { | ||
| test("splits a batch larger than chunkSize into multiple chunks", () => { | ||
| const goals = Array.from({ length: 5 }, (_, i) => goal(`g${i}`)); | ||
|
|
||
| const { batchChunks, individualGoals } = groupGoalsForBulkAnalytics( | ||
| goals, | ||
| [], | ||
| "2026-01-01", | ||
| 2 | ||
| ); | ||
|
|
||
| expect(individualGoals).toHaveLength(0); | ||
| expect(batchChunks).toHaveLength(3); | ||
| expect(batchChunks.map((chunk) => chunk.goals.length)).toEqual([2, 2, 1]); | ||
| expect(batchChunks.flatMap((chunk) => chunk.goals.map((g) => g.id))).toEqual( | ||
| ["g0", "g1", "g2", "g3", "g4"] | ||
| ); | ||
| }); | ||
|
|
||
| test("routes goals with a goal-level filter to individualGoals", () => { | ||
| const filtered = goal("filtered", [ | ||
| { field: "path", operator: "equals", value: "/pricing" }, | ||
| ]); | ||
| const unfiltered = goal("unfiltered"); | ||
|
|
||
| const { batchChunks, individualGoals } = groupGoalsForBulkAnalytics( | ||
| [filtered, unfiltered], | ||
| [], | ||
| "2026-01-01", | ||
| 255 | ||
| ); | ||
|
|
||
| expect(individualGoals).toEqual([ | ||
| { goal: filtered, combinedFilters: filtered.filters }, | ||
| ]); | ||
| expect(batchChunks).toHaveLength(1); | ||
| expect(batchChunks[0]?.goals).toEqual([unfiltered]); | ||
| }); | ||
|
|
||
| test("routes every goal to individualGoals when a request-level filter applies", () => { | ||
| const goals = [goal("a"), goal("b")]; | ||
| const requestFilters: TestFilter[] = [ | ||
| { field: "country", operator: "equals", value: "US" }, | ||
| ]; | ||
|
|
||
| const { batchChunks, individualGoals } = groupGoalsForBulkAnalytics( | ||
| goals, | ||
| requestFilters, | ||
| "2026-01-01", | ||
| 255 | ||
| ); | ||
|
|
||
| expect(batchChunks).toHaveLength(0); | ||
| expect(individualGoals).toHaveLength(2); | ||
| for (const entry of individualGoals) { | ||
| expect(entry.combinedFilters).toEqual(requestFilters); | ||
| } | ||
| }); | ||
|
|
||
| test("groups filter-free goals by effective start date into separate chunks", () => { | ||
| const recent = goal("recent"); | ||
| const backfilled: TestGoal = { | ||
| id: "backfilled", | ||
| createdAt: new Date("2026-01-15"), | ||
| ignoreHistoricData: true, | ||
| filters: null, | ||
| }; | ||
|
|
||
| const { batchChunks } = groupGoalsForBulkAnalytics( | ||
| [recent, backfilled], | ||
| [], | ||
| "2026-01-01", | ||
| 255 | ||
| ); | ||
|
|
||
| expect(batchChunks).toHaveLength(2); | ||
| const dates = batchChunks.map((chunk) => chunk.effectiveStartDate).sort(); | ||
| expect(dates).toEqual(["2026-01-01", "2026-01-15"]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| export interface GoalForGrouping { | ||
| createdAt: Date | null; | ||
| filters: unknown; | ||
| id: string; | ||
| ignoreHistoricData: boolean; | ||
| } | ||
|
|
||
| export const getEffectiveStartDate = ( | ||
| requestedStartDate: string, | ||
| createdAt: Date | null, | ||
| ignoreHistoricData: boolean | ||
| ): string => { | ||
| if (!(ignoreHistoricData && createdAt)) { | ||
| return requestedStartDate; | ||
| } | ||
|
|
||
| const createdDate = new Date(createdAt).toISOString().split("T")[0]; | ||
| return new Date(requestedStartDate) > new Date(createdDate) | ||
| ? requestedStartDate | ||
| : createdDate; | ||
| }; | ||
|
|
||
| export interface BatchChunk<TGoal extends GoalForGrouping> { | ||
| effectiveStartDate: string; | ||
| goals: TGoal[]; | ||
| } | ||
|
|
||
| export interface GroupedGoalsForBulkAnalytics< | ||
| TGoal extends GoalForGrouping, | ||
| TFilter, | ||
| > { | ||
| batchChunks: BatchChunk<TGoal>[]; | ||
| individualGoals: { combinedFilters: TFilter[]; goal: TGoal }[]; | ||
| } | ||
|
|
||
| export function groupGoalsForBulkAnalytics< | ||
| TGoal extends GoalForGrouping, | ||
| TFilter, | ||
| >( | ||
| goalsList: TGoal[], | ||
| requestFilters: TFilter[], | ||
| startDate: string, | ||
| chunkSize: number | ||
| ): GroupedGoalsForBulkAnalytics<TGoal, TFilter> { | ||
| const batchGroups = new Map<string, TGoal[]>(); | ||
| const individualGoals: { combinedFilters: TFilter[]; goal: TGoal }[] = []; | ||
|
|
||
| for (const goal of goalsList) { | ||
| const filters = (goal.filters as TFilter[]) || []; | ||
| const combinedFilters = [...requestFilters, ...filters]; | ||
| if (combinedFilters.length > 0) { | ||
| individualGoals.push({ goal, combinedFilters }); | ||
| continue; | ||
| } | ||
|
|
||
| const effectiveStartDate = getEffectiveStartDate( | ||
| startDate, | ||
| goal.createdAt, | ||
| goal.ignoreHistoricData | ||
| ); | ||
| const group = batchGroups.get(effectiveStartDate) ?? []; | ||
| group.push(goal); | ||
| batchGroups.set(effectiveStartDate, group); | ||
| } | ||
|
|
||
| const batchChunks: BatchChunk<TGoal>[] = []; | ||
| for (const [effectiveStartDate, groupGoals] of batchGroups) { | ||
| for (let i = 0; i < groupGoals.length; i += chunkSize) { | ||
| batchChunks.push({ | ||
| effectiveStartDate, | ||
| goals: groupGoals.slice(i, i + chunkSize), | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return { batchChunks, individualGoals }; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.