: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
fix(error-tracking): filter property breakdowns (#83082)
Hugues Pouillot09b84e9b2958
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 35d0b664dcad..3f17e15196ff 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -20652,6 +20652,9 @@"dateRange": {"$ref": "#/definitions/DateRange"},+ "filterGroup": {+ "$ref": "#/definitions/PropertyGroupFilter"+ },"filterTestAccounts": {"type": "boolean"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 9ee27e057c22..d33d1d279310 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3832,6 +3832,7 @@ export interface ErrorTrackingBreakdownsQuery extends DataNode<ErrorTrackingBreaissueId: ErrorTrackingIssue['id']breakdownProperties: string[]dateRange?: DateRange+ filterGroup?: PropertyGroupFilterfilterTestAccounts?: booleanmaxValuesPerProperty?: integer}diff --git a/posthog/schema.py b/posthog/schema.pyindex bfff47b14f7e..94cb423925bb 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -25327,22 +25327,6 @@ class EnsembleDetectorConfig(BaseModel):type: Literal["ensemble"] = "ensemble"-class ErrorTrackingBreakdownsQuery(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- breakdownProperties: list[str]- dateRange: DateRange | None = None- filterTestAccounts: bool | None = None- issueId: str- kind: Literal["ErrorTrackingBreakdownsQuery"] = "ErrorTrackingBreakdownsQuery"- maxValuesPerProperty: int | None = None- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- response: ErrorTrackingBreakdownsQueryResponse | None = None- tags: QueryLogTags | None = None- version: float | None = Field(default=None, description="version of the node, used for schema migrations")--class ErrorTrackingCorrelatedIssue(BaseModel):model_config = ConfigDict(extra="forbid",@@ -27021,6 +27005,23 @@ class DetectorConfig() = Field(..., description="Detector configuration types", discriminator="type")+class ErrorTrackingBreakdownsQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ breakdownProperties: list[str]+ dateRange: DateRange | None = None+ filterGroup: PropertyGroupFilter | None = None+ filterTestAccounts: bool | None = None+ issueId: str+ kind: Literal["ErrorTrackingBreakdownsQuery"] = "ErrorTrackingBreakdownsQuery"+ maxValuesPerProperty: int | None = None+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ response: ErrorTrackingBreakdownsQueryResponse | None = None+ tags: QueryLogTags | None = None+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")++class ErrorTrackingIssueCorrelationQuery(BaseModel):model_config = ConfigDict(extra="forbid",diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_breakdowns_query_runner.py b/products/error_tracking/backend/hogql_queries/error_tracking_breakdowns_query_runner.pyindex 9b1bf0e12e5a..4f636d5715ab 100644--- a/products/error_tracking/backend/hogql_queries/error_tracking_breakdowns_query_runner.py+++ b/products/error_tracking/backend/hogql_queries/error_tracking_breakdowns_query_runner.py@@ -214,6 +214,9 @@ class ErrorTrackingBreakdownsQueryRunner(for prop in self.team.test_account_filters or []:conditions.append(property_to_expr(prop, self.team))+ if self.query.filterGroup:+ conditions.append(property_to_expr(self.query.filterGroup, self.team))+return ast.And(exprs=conditions)def _calculate(self):diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_breakdowns_query_runner.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_breakdowns_query_runner.pyindex 883ebb52977c..1fcbb82ac6e7 100644--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_breakdowns_query_runner.py+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_breakdowns_query_runner.py@@ -9,7 +9,16 @@ from posthog.test.base import (from rest_framework.exceptions import ValidationError-from posthog.schema import BreakdownValue, DateRange, ErrorTrackingBreakdownsQuery+from posthog.schema import (+ BreakdownValue,+ DateRange,+ ErrorTrackingBreakdownsQuery,+ EventPropertyFilter,+ FilterLogicalOperator,+ PropertyGroupFilter,+ PropertyGroupFilterValue,+ PropertyOperator,+)from products.error_tracking.backend.hogql_queries.error_tracking_breakdowns_query_runner import (ErrorTrackingBreakdownsQueryRunner,@@ -158,6 +167,49 @@ class TestErrorTrackingBreakdownsQueryRunner(ClickhouseTestMixin, APIBaseTest):os_data.values, key=lambda x: x.value)+ @freeze_time("2024-01-10T12:00:00Z")+ def test_breakdown_respects_property_filters(self) -> None:+ self.create_issue(self.issue_id, self.fingerprint)++ for _ in range(5):+ self.create_exception_event("chrome_user", {"$browser": "Chrome", "$os": "Windows"})+ for _ in range(3):+ self.create_exception_event("firefox_user", {"$browser": "Firefox", "$os": "macOS"})++ flush_persons_and_events()++ runner = ErrorTrackingBreakdownsQueryRunner(+ team=self.team,+ query=ErrorTrackingBreakdownsQuery(+ kind="ErrorTrackingBreakdownsQuery",+ issueId=self.issue_id,+ breakdownProperties=["$browser", "$os"],+ dateRange=DateRange(date_from="-7d"),+ filterGroup=PropertyGroupFilter(+ type=FilterLogicalOperator.AND_,+ values=[+ PropertyGroupFilterValue(+ type=FilterLogicalOperator.AND_,+ values=[+ EventPropertyFilter(+ key="$browser",+ value=["Chrome"],+ operator=PropertyOperator.EXACT,+ )+ ],+ )+ ],+ ),+ ),+ )++ response = runner.calculate()++ assert response.results["$browser"].total_count == 5+ assert response.results["$browser"].values == [BreakdownValue(value="Chrome", count=5)]+ assert response.results["$os"].total_count == 5+ assert response.results["$os"].values == [BreakdownValue(value="Windows", count=5)]+@freeze_time("2024-01-10T12:00:00Z")@snapshot_clickhouse_queriesdef test_breakdown_with_null_values(self):diff --git a/products/error_tracking/frontend/components/Breakdowns/miniBreakdownsLogic.test.ts b/products/error_tracking/frontend/components/Breakdowns/miniBreakdownsLogic.test.tsindex 72ff59087a8f..49ec822192cc 100644--- a/products/error_tracking/frontend/components/Breakdowns/miniBreakdownsLogic.test.ts+++ b/products/error_tracking/frontend/components/Breakdowns/miniBreakdownsLogic.test.ts@@ -157,6 +157,30 @@ describe('miniBreakdownsLogic', () => {expect(breakdowns.values.selectedBreakdownProperty).toBeNull()})+ it('reloads breakdowns and details with the active property filters', async () => {+ await expectLogic(breakdowns).toFinishAllListeners()+ const queryMock = jest.mocked(api.query)+ const previousBreakdownQueryCount = queryMock.mock.calls.filter(+ ([query]) => query.kind === 'ErrorTrackingBreakdownsQuery'+ ).length++ await expectLogic(breakdowns, () => {+ filters.actions.addPropertyFilter('$browser', 'Chrome')+ }).toFinishAllListeners()++ const breakdownQueries = queryMock.mock.calls+ .map(([query]) => query)+ .filter((query): query is ErrorTrackingBreakdownsQuery => query.kind === 'ErrorTrackingBreakdownsQuery')+ expect(breakdownQueries).toHaveLength(previousBreakdownQueryCount + 1)+ expect(breakdownQueries.at(-1)?.filterGroup).toEqual(filters.values.filterGroup)++ await expectLogic(breakdowns, () => {+ breakdowns.actions.openBreakdownDetails(BREAKDOWN_PRESETS[0])+ }).toFinishAllListeners()+ const detailsQuery = queryMock.mock.calls.at(-1)?.[0] as ErrorTrackingBreakdownsQuery+ expect(detailsQuery.filterGroup).toEqual(filters.values.filterGroup)+ })+it('discards details returned for a property that was superseded', async () => {await expectLogic(breakdowns).toFinishAllListeners()let resolveFirstRequest: (response: ErrorTrackingBreakdownsQueryResponse) => void = () => {}diff --git a/products/error_tracking/frontend/components/Breakdowns/miniBreakdownsLogic.ts b/products/error_tracking/frontend/components/Breakdowns/miniBreakdownsLogic.tsindex 959150013275..61408b0ab8fa 100644--- a/products/error_tracking/frontend/components/Breakdowns/miniBreakdownsLogic.ts+++ b/products/error_tracking/frontend/components/Breakdowns/miniBreakdownsLogic.ts@@ -16,6 +16,7 @@ import {ErrorTrackingBreakdownsQueryResponse,} from '~/queries/schema/schema-general'import { getCoreFilterDefinition } from '~/taxonomy/helpers'+import { UniversalFiltersGroup } from '~/types'import { errorTrackingBreakdownsQuery } from '../../queries'import { errorTrackingIssueSceneLogic } from '../../scenes/ErrorTrackingIssueScene/errorTrackingIssueSceneLogic'@@ -100,6 +101,7 @@ export function buildBreakdownProperties(selectedEventBreakdownProperties: Breakexport interface miniBreakdownsLogicValues {selectedEvent: ErrorEventType | null // errorTrackingIssueSceneLogicdateRange: DateRange // issueFiltersLogic+ filterGroup: UniversalFiltersGroup // issueFiltersLogicfilterTestAccounts: boolean // issueFiltersLogicisCloudOrDev: boolean | undefined // preflightLogicbreakdownDetails: ErrorTrackingBreakdownsQueryResponse | null@@ -206,7 +208,7 @@ export const miniBreakdownsLogic = kea<miniBreakdownsLogicType>([connect((props: MiniBreakdownsLogicProps) => ({values: [issueFiltersLogic({ logicKey: ERROR_TRACKING_ISSUE_SCENE_LOGIC_KEY }),- ['dateRange', 'filterTestAccounts'],+ ['dateRange', 'filterGroup', 'filterTestAccounts'],errorTrackingIssueSceneLogic({ id: props.issueId }),['selectedEvent'],preflightLogic,@@ -253,6 +255,7 @@ export const miniBreakdownsLogic = kea<miniBreakdownsLogicType>([errorTrackingBreakdownsQuery({issueId: props.issueId,dateRange: values.dateRange,+ filterGroup: values.filterGroup,filterTestAccounts: values.filterTestAccounts,breakdownProperties: [property],maxValuesPerProperty: BREAKDOWN_DETAILS_LIMIT,@@ -271,12 +274,13 @@ export const miniBreakdownsLogic = kea<miniBreakdownsLogicType>([await breakpoint(100)const startTime = Date.now()// Read connected values before the request because either connected logic may unmount while it runs.- const { dateRange, filterTestAccounts } = values+ const { dateRange, filterGroup, filterTestAccounts } = valuesconst breakdownProperties = values.breakdownProperties.map((preset) => preset.property)const result = await api.query(errorTrackingBreakdownsQuery({issueId: props.issueId,dateRange,+ filterGroup,filterTestAccounts,breakdownProperties,maxValuesPerProperty: LIMIT_ITEMS,@@ -354,6 +358,11 @@ export const miniBreakdownsLogic = kea<miniBreakdownsLogicType>([actions.loadResponse()}},+ filterGroup: (value, oldValue) => {+ if (oldValue !== undefined && value !== oldValue) {+ actions.loadResponse()+ }+ },selectedEventBreakdownProperties: (value: BreakdownPreset[], oldValue: BreakdownPreset[] | undefined) => {const propertyNames = value.map(({ property }) => property).join('\0')const previousPropertyNames = oldValue?.map(({ property }) => property).join('\0')diff --git a/products/error_tracking/frontend/queries.ts b/products/error_tracking/frontend/queries.tsindex 3b7c8da34609..1de2a46a1cd5 100644--- a/products/error_tracking/frontend/queries.ts+++ b/products/error_tracking/frontend/queries.ts@@ -288,12 +288,14 @@ export const errorTrackingBreakdownsQuery = ({issueId,breakdownProperties,dateRange,+ filterGroup,filterTestAccounts,maxValuesPerProperty = LIMIT_ITEMS,}: {issueId: stringbreakdownProperties: string[]dateRange: DateRange+ filterGroup: UniversalFiltersGroupfilterTestAccounts: booleanmaxValuesPerProperty?: number}): ErrorTrackingBreakdownsQuery => {@@ -302,6 +304,7 @@ export const errorTrackingBreakdownsQuery = ({issueId,breakdownProperties,dateRange,+ filterGroup: filterGroup as PropertyGroupFilter,filterTestAccounts,maxValuesPerProperty,tags: {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d8c3e166fa48..5dff1ca1e5df 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29429,6 +29429,7 @@ export namespace Schemas {export interface ErrorTrackingBreakdownsQuery {breakdownProperties: string[];dateRange?: DateRange | null;+ filterGroup?: PropertyGroupFilter | null;filterTestAccounts?: boolean | null;issueId: string;kind?: 'ErrorTrackingBreakdownsQuery';