Skip to content

: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.

fix(customer-analytics): stop account spend charts fetching a missing insight (#122188)

posthog[bot]f376a00d6150
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index c9bc30447df3..47956f34e9ec 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -214,7 +214,7 @@ Each per-tab logic key ends in an `instanceId` segment (`accountId:instanceId`,
**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `AccountDetailTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountNotebooksLogic({ accountId })`, `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountConversationsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components so both resolve to the same keyed instance. `accountLinksLogic` mounts through the always-rendered sidebar. `CustomerTasksMount` keeps the account task logic mounted only when `CUSTOMER_ANALYTICS_CUSTOMER_TASKS` is enabled. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live. Flag-gated tabs load only when their flag is enabled.
-The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. Its "Access level" and "Last logged in" headers sort (server-side for US orgs via `ordering`, client-side for cached EU rows; sorting is not written to the URL since it's per expanded row), and the "Access level" header carries a filter menu (owner / admin / member checkboxes, count badge) built with the shared `columnValueFilter` helper in `components/columnValueFilter.tsx`, which turns any enumerated column into a header filter and leaves the actual filtering to the caller. Row checkboxes keep selected email addresses across pages. The search field and bulk controls share one wrapping toolbar row, so selection does not add a row above the table. The bulk action copies each selected address on a separate line. A user without an email address cannot be selected. Staff also see an "Impersonate" action that opens the user's Django admin detail page in the member's US or EU cloud. Outside PostHog Cloud, the action stays on the current origin so local and self-hosted users can test their own admin. The **Usage/Spend** tabs are different: their insight results live in `dataNodeLogic`/`dataVisualizationLogic`. After each `accountBillingLogic` loads its saved-insight metadata, it mounts those result logics immediately. Because the expanded-row root mounts both billing kinds, all Usage and Spend queries start when the account expands instead of waiting for a tab click. The result logics stay mounted until the row collapses. Changing the date range replaces each insight's preload and aborts work under the previous query key. The tab body reuses the same keyed logics and attaches them to `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this directly, and the fallback `<Query>` path uses `attachTo={accountBillingLogic-instance}` plus matching insight context. This prevents duplicate loads and keeps results across tab switches. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)
+The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. Its "Access level" and "Last logged in" headers sort (server-side for US orgs via `ordering`, client-side for cached EU rows; sorting is not written to the URL since it's per expanded row), and the "Access level" header carries a filter menu (owner / admin / member checkboxes, count badge) built with the shared `columnValueFilter` helper in `components/columnValueFilter.tsx`, which turns any enumerated column into a header filter and leaves the actual filtering to the caller. Row checkboxes keep selected email addresses across pages. The search field and bulk controls share one wrapping toolbar row, so selection does not add a row above the table. The bulk action copies each selected address on a separate line. A user without an email address cannot be selected. Staff also see an "Impersonate" action that opens the user's Django admin detail page in the member's US or EU cloud. Outside PostHog Cloud, the action stays on the current origin so local and self-hosted users can test their own admin. The **Usage/Spend** tabs are different: their insight results live in `dataNodeLogic`/`dataVisualizationLogic`. After each `accountBillingLogic` loads its saved-insight metadata, it mounts those result logics immediately. Because the expanded-row root mounts both billing kinds, all Usage and Spend queries start when the account expands instead of waiting for a tab click. The result logics stay mounted until the row collapses. Changing the date range replaces each insight's preload and aborts work under the previous query key. The tab body reuses the same keyed logics and attaches them to `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this directly, and the fallback `<Query>` path uses `attachTo={accountBillingLogic-instance}` plus matching insight context. Query keys start with `new-`, so the fallback's `insightLogic` treats the key as unsaved and does not fetch it as an insight short ID. This prevents duplicate loads and keeps results across tab switches. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)
Usage aggregation lives in `billingUsageQuery.ts`: the Usage tab wraps the saved daily query to sum its configured value columns into day/week/month buckets, preserving account/date variables and query tags. `accountBillingLogic.displayInsights` supplies the same derived query to preloads and rendered charts. The interval is part of the cache key, survives tab switches, and defaults to daily. `AccountDetailTabs` holds a usage-logic mount so the detail scene keeps that state too. Weeks start Monday; edge buckets include only dates within the selected range. Automatic usage charts render as account-owned line charts so the series controls wrap outside the plot. Spend retains its saved calculations.
diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
index 83be2f1656e0..37ff633775a9 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
@@ -2,12 +2,13 @@ import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import api from 'lib/api'
+import { insightLogic } from 'scenes/insights/insightLogic'
import { insightsApi } from 'scenes/insights/utils/api'
import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { ChartDisplayType, type InsightModel } from '~/types'
+import { ChartDisplayType, type InsightModel, type InsightShortId } from '~/types'
import {
AccountBillingKind,
@@ -177,6 +178,24 @@ describe('accountBillingLogic', () => {
expect(nextQueryKey).toContain('2024-01-31')
})
+ it('gives the fallback chart an insight key that does not fetch a saved insight', async () => {
+ mountForKind()
+ await expectLogic(logic).toFinishAllListeners()
+
+ for (const shortId of BILLING_INSIGHT_SHORT_IDS[kind]) {
+ const queryKey = logic.values.queryKeyFor(shortId)
+ const fallbackInsightLogic = insightLogic({
+ dashboardItemId: queryKey as InsightShortId,
+ dataNodeCollectionId: queryKey,
+ })
+ fallbackInsightLogic.mount()
+ await expectLogic(fallbackInsightLogic).toFinishAllListeners()
+ fallbackInsightLogic.unmount()
+ }
+
+ expect(insightsApi.getByShortId).toHaveBeenCalledTimes(BILLING_INSIGHT_SHORT_IDS[kind].length)
+ })
+
it('replaces stale preloads when the date range changes', async () => {
mountForKind()
await expectLogic(logic).toFinishAllListeners()
diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
index 63ef19ac9229..c740633a0c14 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
@@ -435,6 +435,8 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
],
// The embedded <Query> only refetches when its query changes, not when variablesOverride changes — so a date
// change must remount it. Keying on the resolved range gives each insight a key that changes with the range.
+ // The fallback <Query> passes this key as `dashboardItemId`. The `new-` prefix stops insightLogic from
+ // fetching it as a saved insight short ID, which fails as "not found".
queryKeyFor: [
(s) => [
s.resolvedDateRange,
@@ -445,7 +447,7 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
],
(resolvedDateRange: BillingDateRange, accountId, kind, instanceId, interval: BillingUsageInterval) =>
(shortId: string): string =>
- `account-billing-${accountId}-${kind}-${instanceId ?? 'default'}-${shortId}-${resolvedDateRange.date_from}-${resolvedDateRange.date_to}-${interval}`,
+ `new-account-billing-${accountId}-${kind}-${instanceId ?? 'default'}-${shortId}-${resolvedDateRange.date_from}-${resolvedDateRange.date_to}-${interval}`,
],
}),
afterMount(({ actions, props }) => {