: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
feat(endpoints): configure required breakdowns in the UI (#68217)
Jovan Sakovicec6410904c30
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d6029496fce4..323fe018fdde 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6077,9 +6077,9 @@ snapshots:scenes-app-insights-trendsvalue--trends-table-edit--light:hash: v1.k794b7964.11f5d26d2e154d830a64750ea97714230574604cdc71f62afb087303d48b2c5d.nS5B8LoRJrHn6trtCDVBFRg81P0wewpWl5LIimTT6PQscenes-app-insights-trendsvalue--trends-value--dark:- hash: v1.k794b7964.d782e01a1e443c31cd99f08d55621dbd39a848faf0bd87119abcbad04a9fffa1.FL_rdrYD0IOMullBER_dpmu-HcaIYxndjtkikkSLI08+ hash: v1.k794b7964.60aaa2b69df11c4d10d0977fb1ffcf4e9c6034118e8ea933e66c96349cf415b7.TF2oPw_7DetWi0jI_KNBPiiNYai3i9OfA6ta8iGtgMMscenes-app-insights-trendsvalue--trends-value--light:- hash: v1.k794b7964.0e1870fa7a60031d6037f10e43a01381b8ad1500d4ef2227216ec8fb03249603.Jy3H15MG08pGB1NJed2sIqcsWrre7sspN660rvLf0-s+ hash: v1.k794b7964.c3c96277b269a610b8b38db89e9f64190ead964b0ae6325eedba55c21f3b4b6c.qIF7_RMru-e9Xwjg5HI33OsPRr8vmlWhQPPnZ88IyE4scenes-app-insights-trendsvalue--trends-value-breakdown--dark:hash: v1.k794b7964.a64a39497ca66134891338e6584026623461224be2287bb01cf7c8d6a0f5134a.PhrCp9FmhICSYUerB623A2grcjdpkPKrw7TQlMPY4Jkscenes-app-insights-trendsvalue--trends-value-breakdown--light:diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 55c7ad6919fe..5489665c4fba 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2551,6 +2551,8 @@ export interface EndpointType extends WithAccessControl {columns?: { name: string; type: string }[]bucket_overrides?: Record<string, string> | nulltags?: string[]+ /** Breakdown property names that may be omitted on /run. Defaults to [] — every breakdown variable is required. */+ optional_breakdown_properties?: string[]}/** Extends EndpointType with version-specific fields when fetching a specific version */diff --git a/products/endpoints/backend/tests/test_openapi_spec.py b/products/endpoints/backend/tests/test_openapi_spec.pyindex ff361401f4b7..15bce79b64ec 100644--- a/products/endpoints/backend/tests/test_openapi_spec.py+++ b/products/endpoints/backend/tests/test_openapi_spec.py@@ -189,8 +189,9 @@ class TestEndpointOpenAPISpec(ClickhouseTestMixin, APIBaseTest):self.assertNotIn("variables", request_schema.get("required", []))def test_build_variables_schema_marks_breakdown_required_on_insight(self):- """Breakdown variables are enforced at run time on both inline and materialized- insight endpoints, so the spec marks them required on both paths."""+ """The spec marks breakdown variables required on both inline and materialized+ insight endpoints so generated clients always send them; run-time enforcement+ currently applies to materialized endpoints only."""from products.endpoints.backend.openapi import _build_variables_schematrends_query = {diff --git a/products/endpoints/frontend/EndpointHeader.tsx b/products/endpoints/frontend/EndpointHeader.tsxindex 170e2f9ed043..5a9e2074a602 100644--- a/products/endpoints/frontend/EndpointHeader.tsx+++ b/products/endpoints/frontend/EndpointHeader.tsx@@ -15,7 +15,7 @@ import { isInsightVizNode } from '~/queries/utils'import { AccessControlLevel, AccessControlResourceType, EndpointType, EndpointVersionType } from '~/types'import { endpointLogic } from './endpointLogic'-import { endpointSceneLogic } from './endpointSceneLogic'+import { endpointSceneLogic, extractBreakdownPropertyNames } from './endpointSceneLogic'export const EndpointSceneHeader = (): JSX.Element => {const {@@ -27,11 +27,18 @@ export const EndpointSceneHeader = (): JSX.Element => {bucketOverrides,debugInfoExpanded,dataFreshness,+ optionalBreakdownProperties,} = useValues(endpointSceneLogic)- const { endpointName, endpointDescription } = useValues(endpointLogic)+ const { endpointName, endpointDescription, updatingEndpoint } = useValues(endpointLogic)const { setEndpointDescription, updateEndpoint } = useActions(endpointLogic)- const { setLocalQuery, setDataFreshness, setIsMaterialized, resetBucketOverrides, setDebugInfoExpanded } =- useActions(endpointSceneLogic)+ const {+ setLocalQuery,+ setDataFreshness,+ setIsMaterialized,+ resetBucketOverrides,+ resetOptionalBreakdownProperties,+ setDebugInfoExpanded,+ } = useActions(endpointSceneLogic)const { superpowersEnabled } = useValues(superpowersLogic)// SceneTitleSection takes a boolean `canEdit` rather than disabled/disabledReason, so we can't@@ -57,13 +64,20 @@ export const EndpointSceneHeader = (): JSX.Element => {const hasIsMaterializedChange = isMaterialized !== null && isMaterialized !== baseIsMaterializedconst baseBucketOverrides = viewingVersion?.bucket_overrides ?? endpoint?.bucket_overrides ?? {}const hasBucketOverridesChange = !objectsEqual(bucketOverrides, baseBucketOverrides)+ const baseOptionalBreakdowns =+ viewingVersion?.optional_breakdown_properties ?? endpoint?.optional_breakdown_properties ?? []+ const hasOptionalBreakdownChange = !objectsEqual(+ [...optionalBreakdownProperties].sort(),+ [...baseOptionalBreakdowns].sort()+ )const hasChanges =hasNameChange ||hasDescriptionChange ||hasQueryChange ||hasDataFreshnessChange ||hasIsMaterializedChange ||- hasBucketOverridesChange+ hasBucketOverridesChange ||+ hasOptionalBreakdownChangeconst handleSave = (): void => {let queryToSave = (localQuery || endpoint?.query) as any@@ -76,12 +90,20 @@ export const EndpointSceneHeader = (): JSX.Element => {return}+ // Prune the optional list against the query actually being saved — a query edit can+ // remove a breakdown after it was marked optional, and the backend rejects unknown names.+ const savedQueryBreakdowns = extractBreakdownPropertyNames(+ hasQueryChange ? queryToSave : (viewingVersion?.query ?? endpoint.query)+ )+ const prunedOptionalBreakdowns = optionalBreakdownProperties.filter((p) => savedQueryBreakdowns.includes(p))+const updatePayload: Partial<EndpointRequest> = {description: hasDescriptionChange ? endpointDescription : undefined,data_freshness_seconds: hasDataFreshnessChange ? dataFreshness : undefined,query: hasQueryChange ? queryToSave : undefined,is_materialized: hasIsMaterializedChange ? isMaterialized : undefined,bucket_overrides: hasBucketOverridesChange ? bucketOverrides : undefined,+ optional_breakdown_properties: hasOptionalBreakdownChange ? prunedOptionalBreakdowns : undefined,}updateEndpoint(endpoint.name, updatePayload, targetVersion ? { version: targetVersion } : undefined)@@ -99,6 +121,9 @@ export const EndpointSceneHeader = (): JSX.Element => {setIsMaterialized(null)setLocalQuery(null)resetBucketOverrides(viewingVersion?.bucket_overrides ?? endpoint.bucket_overrides ?? {})+ resetOptionalBreakdownProperties(+ viewingVersion?.optional_breakdown_properties ?? endpoint.optional_breakdown_properties ?? []+ )}return (@@ -144,14 +169,17 @@ export const EndpointSceneHeader = (): JSX.Element => {<LemonButtontype="primary"onClick={handleSave}+ loading={updatingEndpoint}disabledReason={!endpoint? 'Endpoint not loaded'- : !hasChanges- ? 'No changes to save'- : hasQueryChange && targetVersion- ? 'Query can only be changed when on the latest version'- : undefined+ : updatingEndpoint+ ? 'Update in progress'+ : !hasChanges+ ? 'No changes to save'+ : hasQueryChange && targetVersion+ ? 'Query can only be changed when on the latest version'+ : undefined}>Updatediff --git a/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx b/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsxindex a9fe53bb9d8b..9ceac1426a83 100644--- a/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx+++ b/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx@@ -1,10 +1,11 @@import { useActions, useValues } from 'kea'import { useState } from 'react'-import { IconClock, IconDatabase, IconInfo, IconList, IconRefresh, IconSparkles } from '@posthog/icons'+import { IconBrackets, IconClock, IconDatabase, IconInfo, IconList, IconRefresh, IconSparkles } from '@posthog/icons'import {LemonBanner,LemonButton,+ LemonCheckbox,LemonCollapse,LemonSelect,LemonSkeleton,@@ -23,9 +24,20 @@ import { NodeKind } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { endpointLogic } from '../endpointLogic'-import { endpointSceneLogic, MaterializationPreview } from '../endpointSceneLogic'+import { endpointSceneLogic, extractBreakdownPropertyNames, MaterializationPreview } from '../endpointSceneLogic'import { MaterializationSuggestionModal } from '../MaterializationSuggestionModal'+// Names where flipping a breakdown to optional is most likely a customer-data leak — show+// a soft warning when the user does so. Not a hard block; the author may have legitimate+// reasons (e.g. an internal-only endpoint). Keep this list short and conservative; false+// positives are cheap, false negatives cost data.+const SENSITIVE_BREAKDOWN_NAME_PATTERNS = ['team', 'account', 'customer', 'tenant', 'user_id', 'org']++function isSensitiveBreakdownName(name: string): boolean {+ const lower = name.toLowerCase()+ return SENSITIVE_BREAKDOWN_NAME_PATTERNS.some((p) => lower.includes(p))+}+const DATA_FRESHNESS_OPTIONS: { value: number; label: string }[] = [{ value: 900, label: '15 minutes' },{ value: 1800, label: '30 minutes' },@@ -68,13 +80,15 @@ function getStatusTagType(status: string | undefined): 'success' | 'danger' | 'wexport function EndpointConfiguration(): JSX.Element {const { endpoint } = useValues(endpointLogic)- const { setDataFreshness } = useActions(endpointSceneLogic)+ const { setDataFreshness, toggleBreakdownOptional } = useActions(endpointSceneLogic)const {dataFreshness,viewingVersion,materializationPreview,materializationPreviewLoading,isMaterialized: localIsMaterialized,+ currentQuery,+ optionalBreakdownProperties,} = useValues(endpointSceneLogic)const { loadMaterializationPreview } = useActions(endpointSceneLogic)const [leftActiveKeys, setLeftActiveKeys] = useState<string[]>(['materialization'])@@ -89,6 +103,8 @@ export function EndpointConfiguration(): JSX.Element {const isMaterialized = localIsMaterialized ?? baseIsMaterializedconst materializationExpanded = leftActiveKeys.includes('materialization')+ const breakdownProperties = extractBreakdownPropertyNames(currentQuery)+return (<div className="flex gap-6">{/* Left column — settings (fixed width) */}@@ -141,6 +157,29 @@ export function EndpointConfiguration(): JSX.Element {</div>),},+ ...(breakdownProperties.length > 0+ ? [+ {+ key: 'variables',+ header: (+ <div className="flex items-center gap-2">+ <IconBrackets className="text-lg" />+ <span>Variables</span>+ <Tooltip title="Required variables must be passed on every execution. Optional ones may be omitted; the response aggregates across every value.">+ <IconInfo className="text-lg text-secondary" />+ </Tooltip>+ </div>+ ),+ content: (+ <BreakdownRequirementContent+ breakdownProperties={breakdownProperties}+ optionalBreakdownProperties={optionalBreakdownProperties}+ onToggle={toggleBreakdownOptional}+ />+ ),+ },+ ]+ : []),]}/></div>@@ -200,6 +239,61 @@ export function EndpointConfiguration(): JSX.Element {)}+function BreakdownRequirementContent({+ breakdownProperties,+ optionalBreakdownProperties,+ onToggle,+}: {+ breakdownProperties: string[]+ optionalBreakdownProperties: string[]+ onToggle: (property: string) => void+}): JSX.Element {+ const sensitiveMarkedOptional = optionalBreakdownProperties.filter(+ (p) => breakdownProperties.includes(p) && isSensitiveBreakdownName(p)+ )+ return (+ <div className="flex flex-col gap-3 p-1">+ <p className="text-sm text-secondary m-0">+ Uncheck <strong>Required</strong> to let callers omit a breakdown — the response then aggregates across+ every value.+ </p>+ <div className="flex flex-col gap-2">+ {breakdownProperties.map((property) => {+ const isOptional = optionalBreakdownProperties.includes(property)+ return (+ <div+ key={property}+ className="flex items-center justify-between gap-3 p-3 bg-accent-3000 border border-border rounded"+ >+ <div className="flex flex-col">+ <code className="text-sm">{property}</code>+ <span className="text-xs text-secondary">+ {isOptional+ ? 'May be omitted — aggregates across every value.'+ : 'Must be passed on every execution.'}+ </span>+ </div>+ <LemonCheckbox+ checked={!isOptional}+ onChange={() => onToggle(property)}+ label="Required"+ bordered+ />+ </div>+ )+ })}+ </div>+ {sensitiveMarkedOptional.length > 0 && (+ <LemonBanner type="warning">+ <strong>{sensitiveMarkedOptional.map((p) => `"${p}"`).join(', ')}</strong> looks like it identifies+ a tenant. Marking it optional lets callers execute this endpoint without that filter — double-check+ it isn't customer-facing.+ </LemonBanner>+ )}+ </div>+ )+}+function ExecutionQueryPanel({materializationPreview,}: {diff --git a/products/endpoints/frontend/endpointLogic.tsx b/products/endpoints/frontend/endpointLogic.tsxindex ab672eedf8be..853997031379 100644--- a/products/endpoints/frontend/endpointLogic.tsx+++ b/products/endpoints/frontend/endpointLogic.tsx@@ -112,6 +112,14 @@ export const endpointLogic = kea<endpointLogicType>([createEndpointSuccess: () => null,},],+ updatingEndpoint: [+ false,+ {+ updateEndpoint: () => true,+ updateEndpointSuccess: () => false,+ updateEndpointFailure: () => false,+ },+ ],// Clear stale endpoint data immediately when loading a new endpointendpoint: [null as EndpointVersionType | null,diff --git a/products/endpoints/frontend/endpointSceneLogic.test.ts b/products/endpoints/frontend/endpointSceneLogic.test.tsindex 92982c16673e..1037aa16cd13 100644--- a/products/endpoints/frontend/endpointSceneLogic.test.ts+++ b/products/endpoints/frontend/endpointSceneLogic.test.ts@@ -7,7 +7,7 @@ import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'-import { endpointSceneLogic, EndpointTab } from './endpointSceneLogic'+import { endpointSceneLogic, EndpointTab, extractBreakdownPropertyNames } from './endpointSceneLogic'import { endpointsMaterializationSuggestionCreate } from './generated/api'jest.mock('lib/api', () => ({@@ -147,6 +147,68 @@ describe('endpointSceneLogic', () => {})})+ describe('extractBreakdownPropertyNames', () => {+ // Must match the backend's iter_breakdowns, which stringifies every entry (str(name)),+ // so numeric legacy breakdowns (e.g. cohort IDs) land in the OpenAPI required set as strings+ test.each([+ ['legacy string', { breakdown: '$browser', breakdown_type: 'event' }, ['$browser']],+ ['legacy numeric cohort', { breakdown: 2, breakdown_type: 'cohort' }, ['2']],+ ['legacy numeric list', { breakdown: [2, 5], breakdown_type: 'cohort' }, ['2', '5']],+ ['breakdowns form', { breakdowns: [{ property: '$browser' }, { property: 7 }] }, ['$browser', '7']],+ ])('%s', (_name, breakdownFilter, expected) => {+ expect(extractBreakdownPropertyNames({ kind: 'TrendsQuery', breakdownFilter })).toEqual(expected)+ })+ })++ describe('optionalBreakdownProperties reducer', () => {+ it('seeds from the loaded endpoint', async () => {+ const endpointWithOptional = { ...endpoint, optional_breakdown_properties: ['$browser'] }+ await expectLogic(logic, () => {+ logic.actions.loadEndpointSuccess(endpointWithOptional)+ }).toFinishAllListeners()++ expect(logic.values.optionalBreakdownProperties).toEqual(['$browser'])+ })++ it('toggleBreakdownOptional flips a single property both ways', async () => {+ await expectLogic(logic, () => {+ logic.actions.toggleBreakdownOptional('$browser')+ }).toMatchValues({ optionalBreakdownProperties: ['$browser'] })++ await expectLogic(logic, () => {+ logic.actions.toggleBreakdownOptional('$browser')+ }).toMatchValues({ optionalBreakdownProperties: [] })+ })++ it('toggleBreakdownOptional preserves order across independent properties', async () => {+ await expectLogic(logic, () => {+ logic.actions.toggleBreakdownOptional('$browser')+ logic.actions.toggleBreakdownOptional('$os')+ }).toMatchValues({ optionalBreakdownProperties: ['$browser', '$os'] })++ await expectLogic(logic, () => {+ logic.actions.toggleBreakdownOptional('$browser')+ }).toMatchValues({ optionalBreakdownProperties: ['$os'] })+ })++ it('resetOptionalBreakdownProperties wins on version switch', async () => {+ await expectLogic(logic, () => {+ logic.actions.toggleBreakdownOptional('$browser')+ }).toMatchValues({ optionalBreakdownProperties: ['$browser'] })++ const versionData = {+ ...endpoint,+ version: 2,+ optional_breakdown_properties: ['$os'],+ }+ await expectLogic(logic, () => {+ logic.actions.setViewingVersion(versionData)+ }).toFinishAllListeners()++ expect(logic.values.optionalBreakdownProperties).toEqual(['$os'])+ })+ })+describe('materialization suggestion', () => {const hogqlEndpoint = {...endpoint,diff --git a/products/endpoints/frontend/endpointSceneLogic.tsx b/products/endpoints/frontend/endpointSceneLogic.tsxindex a66e04eeeef3..69b1808d4775 100644--- a/products/endpoints/frontend/endpointSceneLogic.tsx+++ b/products/endpoints/frontend/endpointSceneLogic.tsx@@ -32,15 +32,30 @@ const DEFAULT_DATA_FRESHNESS_SECONDS = 86400// Query types that support user-configurable breakdown filteringconst BREAKDOWN_SUPPORTED_QUERY_TYPES = new Set([NodeKind.TrendsQuery, NodeKind.RetentionQuery])-function getSingleBreakdownProperty(breakdownFilter: any): string | null {- if (breakdownFilter?.breakdown) {- return breakdownFilter.breakdown+export function extractBreakdownPropertyNames(query: unknown): string[] {+ // Single source of truth for reading breakdown property names out of a query on the+ // frontend — mirrors the backend's canonical extractor, including the legacy list form.+ if (!query || typeof query !== 'object') {+ return []}- const breakdowns = breakdownFilter?.breakdowns || []- if (breakdowns.length === 1) {- return breakdowns[0]?.property+ const breakdownFilter = (+ query as { breakdownFilter?: { breakdown?: unknown; breakdowns?: { property?: unknown }[] } | null }+ ).breakdownFilter+ if (!breakdownFilter) {+ return []}- return null+ // Numeric entries (e.g. legacy cohort breakdowns) are stringified like the backend's str(name)+ const asName = (value: unknown): string | null =>+ (typeof value === 'string' || typeof value === 'number') && value ? String(value) : null+ const legacy = breakdownFilter.breakdown+ if (Array.isArray(legacy)) {+ return legacy.map(asName).filter((p): p is string => p !== null)+ }+ const legacyName = asName(legacy)+ if (legacyName !== null) {+ return [legacyName]+ }+ return (breakdownFilter.breakdowns ?? []).map((b) => asName(b?.property)).filter((p): p is string => p !== null)}export function generateEndpointPayload(endpoint: EndpointVersionType | null): Record<string, any> {@@ -75,10 +90,10 @@ export function generateEndpointPayload(endpoint: EndpointVersionType | null): R// Only include breakdown for query types that support itif (queryKind && BREAKDOWN_SUPPORTED_QUERY_TYPES.has(queryKind as NodeKind)) {- const breakdownFilter = (query as any).breakdownFilter || {}- const breakdown = getSingleBreakdownProperty(breakdownFilter)- if (breakdown) {- variablesValues[breakdown] = ''+ const breakdownNames = extractBreakdownPropertyNames(query)+ // The legacy playground payload only supports a single breakdown variable.+ if (breakdownNames.length === 1) {+ variablesValues[breakdownNames[0]] = ''}}@@ -146,6 +161,8 @@ export const endpointSceneLogic = kea<endpointSceneLogicType>([setViewingVersion: (version: EndpointVersionType | null) => ({ version }),setBucketOverride: (column: string, bucketFn: string) => ({ column, bucketFn }),resetBucketOverrides: (overrides: Record<string, string>) => ({ overrides }),+ toggleBreakdownOptional: (property: string) => ({ property }),+ resetOptionalBreakdownProperties: (props: string[]) => ({ props }),setDebugMode: (debugMode: boolean) => ({ debugMode }),setDebugInfoExpanded: (debugInfoExpanded: boolean) => ({ debugInfoExpanded }),loadMaterializationPreview: true,@@ -239,6 +256,15 @@ export const endpointSceneLogic = kea<endpointSceneLogicType>([loadEndpointSuccess: (_, { endpoint }) => endpoint?.bucket_overrides ?? {},},],+ optionalBreakdownProperties: [+ [] as string[],+ {+ toggleBreakdownOptional: (state, { property }) =>+ state.includes(property) ? state.filter((p) => p !== property) : [...state, property],+ resetOptionalBreakdownProperties: (_, { props }) => props,+ loadEndpointSuccess: (_, { endpoint }) => endpoint?.optional_breakdown_properties ?? [],+ },+ ],// Clear stale playground results when switching endpointsendpointResult: [null as string | null,@@ -400,6 +426,7 @@ export const endpointSceneLogic = kea<endpointSceneLogicType>([const initialPayload = generateInitialPayloadJson(endpoint)actions.setPayloadJson(initialPayload)actions.setDataFreshness(endpoint?.data_freshness_seconds ?? DEFAULT_DATA_FRESHNESS_SECONDS)+ actions.resetOptionalBreakdownProperties(endpoint?.optional_breakdown_properties ?? [])const { searchParams, hashParams } = router.values@@ -522,6 +549,11 @@ export const endpointSceneLogic = kea<endpointSceneLogicType>([// Reset bucket overrides to viewed version's valuesactions.resetBucketOverrides(version?.bucket_overrides ?? values.endpoint?.bucket_overrides ?? {})+ // Reset optional breakdowns to viewed version's value (or endpoint's if going back to current)+ actions.resetOptionalBreakdownProperties(+ version?.optional_breakdown_properties ?? values.endpoint?.optional_breakdown_properties ?? []+ )+// Reset data freshness to viewed version's value (or endpoint's if going back to current)actions.setDataFreshness(version?.data_freshness_seconds ??