:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(desktop): batch task summary pages in parallel (#96354)
Paul D'Ambracd4bc84ff238
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 3742a07609eb..d63d747f4fc7 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -2204,10 +2204,10 @@ describe("PostHogAPIClient", () => {return client;}- function page(results: object[], next: string | null = null) {+ function page(results: object[], count: number = results.length) {return {ok: true,- json: async () => ({ count: 0, previous: null, next, results }),+ json: async () => ({ count, previous: null, next: null, results }),};}@@ -2225,46 +2225,34 @@ describe("PostHogAPIClient", () => {expect(fetch).not.toHaveBeenCalled();});- it("returns single-page results without further requests", async () => {+ it("requests the max page size and stops when one page covers the count", async () => {const fetch = buildFetchForPages(page([{ id: "a" }]));await expect(buildClient(fetch).getTaskSummaries(["a"])).resolves.toEqual([{ id: "a" }],);expect(fetch).toHaveBeenCalledTimes(1);+ expect(fetch.mock.calls[0][0]).toMatchObject({+ method: "post",+ path: `${SUMMARIES_PATH}?limit=100&offset=0`,+ });});- it.each([- {- name: "same-host next URL",- nextUrl: `http://localhost:8000${SUMMARIES_PATH}?limit=2&offset=2`,- expectedSecondPath: `${SUMMARIES_PATH}?limit=2&offset=2`,- },- {- name: "cross-host next URL (proxy variance)",- nextUrl: `https://internal.posthog.example${SUMMARIES_PATH}?limit=1&offset=1`,- expectedSecondPath: `${SUMMARIES_PATH}?limit=1&offset=1`,- },- ])(- "follows the next cursor across pages and merges results: $name",- async ({ nextUrl, expectedSecondPath }) => {- const fetch = buildFetchForPages(- page([{ id: "a" }, { id: "b" }], nextUrl),- page([{ id: "c" }]),- );- await expect(- buildClient(fetch).getTaskSummaries(["a", "b", "c"]),- ).resolves.toEqual([{ id: "a" }, { id: "b" }, { id: "c" }]);- expect(fetch).toHaveBeenCalledTimes(2);- expect(fetch.mock.calls[0][0]).toMatchObject({- method: "post",- path: SUMMARIES_PATH,- });- expect(fetch.mock.calls[1][0]).toMatchObject({- method: "post",- path: expectedSecondPath,- });- },- );+ it("fetches remaining pages by offset from count, not by walking next", async () => {+ const fetch = buildFetchForPages(+ page([{ id: "a" }], 250),+ page([{ id: "b" }]),+ page([{ id: "c" }]),+ );+ await expect(+ buildClient(fetch).getTaskSummaries(["a", "b", "c"]),+ ).resolves.toEqual([{ id: "a" }, { id: "b" }, { id: "c" }]);+ expect(fetch).toHaveBeenCalledTimes(3);+ expect(fetch.mock.calls.map((call) => call[0].path)).toEqual([+ `${SUMMARIES_PATH}?limit=100&offset=0`,+ `${SUMMARIES_PATH}?limit=100&offset=100`,+ `${SUMMARIES_PATH}?limit=100&offset=200`,+ ]);+ });it("throws when the server responds non-OK", async () => {const fetch = vi@@ -2275,19 +2263,28 @@ describe("PostHogAPIClient", () => {);});- it("returns partial results when MAX_PAGES is exceeded", async () => {- const fetch = vi- .fn()- .mockResolvedValue(- page(- [{ id: "x" }],- `http://localhost:8000${SUMMARIES_PATH}?offset=1`,- ),- );+ it("caps at MAX_PAGES when the count is unbounded", async () => {+ const fetch = vi.fn().mockResolvedValue(page([{ id: "x" }], 1_000_000));const result = await buildClient(fetch).getTaskSummaries(["a"]);expect(fetch).toHaveBeenCalledTimes(50);expect(result.length).toBe(50);});++ it("caps how many page fetches are in flight at once", async () => {+ let inFlight = 0;+ let maxInFlight = 0;+ const fetch = vi.fn().mockImplementation(async () => {+ inFlight++;+ maxInFlight = Math.max(maxInFlight, inFlight);+ await Promise.resolve();+ inFlight--;+ return page([{ id: "x" }], 2000);+ });+ await buildClient(fetch).getTaskSummaries(["a"]);+ // 20 pages (count 2000 / 100), fetched in bounded batches, never all at once.+ expect(fetch).toHaveBeenCalledTimes(20);+ expect(maxInFlight).toBeLessThanOrEqual(6);+ });});describe("task pins", () => {diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex bb16616f23d8..8390587bd44d 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -3050,15 +3050,22 @@ export class PostHogAPIClient {async getTaskSummaries(ids: string[]) {if (ids.length === 0) return [];- const TASK_SUMMARIES_MAX_PAGES = 50;+ // The endpoint caps a page at 100 rows (TasksPagination.max_limit). Ask for+ // the largest page, then pull any remaining pages in parallel by offset. The+ // old code walked `next` one blocking request at a time, so a large sidebar+ // turned into a chain of serial round-trips on every inbox open.+ const PAGE_LIMIT = 100;+ const MAX_PAGES = 50;const teamId = await this.getTeamId();- const all: Schemas.TaskSummaryDTO[] = [];- let urlPath: string = `/api/projects/${teamId}/tasks/summaries/`;- for (let i = 0; i < TASK_SUMMARIES_MAX_PAGES; i++) {- const url = new URL(`${this.api.baseUrl}${urlPath}`);+ const basePath = `/api/projects/${teamId}/tasks/summaries/`;++ const fetchPage = async (+ offset: number,+ ): Promise<Schemas.PaginatedTaskSummaryDTOList> => {+ const urlPath = `${basePath}?limit=${PAGE_LIMIT}&offset=${offset}`;const response = await this.api.fetcher.fetch({method: "post",- url,+ url: new URL(`${this.api.baseUrl}${urlPath}`),path: urlPath,overrides: {body: JSON.stringify({ ids } satisfies Schemas.TaskSummariesRequest),@@ -3069,17 +3076,31 @@ export class PostHogAPIClient {`Failed to fetch task summaries: ${response.statusText}`,);}- const page =- (await response.json()) as Schemas.PaginatedTaskSummaryDTOList;- all.push(...page.results);- if (!page.next) return all;- const nextUrl = new URL(page.next);- urlPath = `${nextUrl.pathname}${nextUrl.search}`;+ return (await response.json()) as Schemas.PaginatedTaskSummaryDTOList;+ };++ const first = await fetchPage(0);+ const all: Schemas.TaskSummaryDTO[] = [...first.results];+ const capped = Math.min(first.count, PAGE_LIMIT * MAX_PAGES);+ if (first.count > PAGE_LIMIT * MAX_PAGES) {+ log.warn(+ `getTaskSummaries capped at ${MAX_PAGES} pages; returning partial results`,+ { ids: ids.length, count: first.count },+ );+ }+ const offsets: number[] = [];+ for (let offset = PAGE_LIMIT; offset < capped; offset += PAGE_LIMIT) {+ offsets.push(offset);+ }+ // Cap how many page POSTs are in flight at once. A large sidebar can span+ // dozens of pages, and this runs on every poll; an unbounded fan-out would+ // fire them all together (each re-sending the full id list).+ const CONCURRENCY = 6;+ for (let i = 0; i < offsets.length; i += CONCURRENCY) {+ const batch = offsets.slice(i, i + CONCURRENCY);+ const pages = await Promise.all(batch.map((offset) => fetchPage(offset)));+ for (const page of pages) all.push(...page.results);}- log.warn(- `getTaskSummaries hit MAX_PAGES (${TASK_SUMMARIES_MAX_PAGES}); returning partial results`,- { ids: ids.length, returned: all.length },- );return all;}