: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(cohorts): render an unmapped criteria row as empty and recoverable (#78489)
Gustavo H. Strassburgerb039fff46b5e
diff --git a/frontend/src/models/cohortsModel.test.ts b/frontend/src/models/cohortsModel.test.tsindex 33085572f1de..618429aa67d9 100644--- a/frontend/src/models/cohortsModel.test.ts+++ b/frontend/src/models/cohortsModel.test.ts@@ -314,5 +314,44 @@ describe('cohortsModel', () => {value_property: '2024-01-01',})})++ it('canonicalizes a behavioral value the backend only accepts as an alias', () => {+ const cohort = {+ id: 6,+ name: 'Aliased criterion cohort',+ count: 0,+ groups: [],+ is_calculating: false,+ is_static: false,+ filters: {+ properties: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: 'behavioral',+ key: 'purchase',+ value: 'performed_event_multiple_times',+ event_type: 'events',+ operator: 'gte',+ operator_value: 2,+ time_value: 30,+ time_interval: 'day',+ },+ ],+ },+ },+ } as unknown as CohortType++ const result = processCohort(cohort)+ const group = result.filters.properties.values[0]+ // The alias has no ROWS entry, so leaving it verbatim renders the criterion as+ // unsupported even though the backend resolves and queries it. explicit_datetime only+ // gets converted once the value is canonical, and without it validateGroup rejects the+ // row for a missing time window the criterion already carried.+ expect((group as any).values[0]).toMatchObject({+ value: 'performed_event_multiple',+ explicit_datetime: '-30d',+ })+ })})})diff --git a/frontend/src/models/cohortsModel.ts b/frontend/src/models/cohortsModel.tsindex 69dc7a909ce8..671ded2a2eb2 100644--- a/frontend/src/models/cohortsModel.ts+++ b/frontend/src/models/cohortsModel.ts@@ -95,6 +95,15 @@ function convertTimeValueToRelativeTime(criteria: AnyCohortCriteriaType): string}}+// Mirrors BEHAVIORAL_VALUE_ALIASES in posthog/models/property/property.py: values older cohort+// builders stored that the backend still resolves to a canonical behavioral type. The API hands+// them back verbatim, so without this the frontend treats them as unmapped and renders no fields.+// A Map, not an object literal: a stored value of 'constructor' or 'toString' resolves to an+// Object.prototype member on a plain lookup.+const BEHAVIORAL_VALUE_ALIASES = new Map<string, BehavioralEventType>([+ ['performed_event_multiple_times', BehavioralEventType.PerformMultipleEvents],+])+function processCohortCriteria(criteria: AnyCohortCriteriaType): AnyCohortCriteriaType {if (!criteria.type) {return criteria@@ -102,6 +111,10 @@ function processCohortCriteria(criteria: AnyCohortCriteriaType): AnyCohortCriterconst processedCriteria = { ...criteria }+ if (criteria.type === BehavioralFilterKey.Behavioral && typeof criteria.value === 'string') {+ processedCriteria.value = BEHAVIORAL_VALUE_ALIASES.get(criteria.value) ?? criteria.value+ }+if ([BehavioralFilterKey.Cohort, BehavioralFilterKey.Person, BehavioralFilterKey.PersonMetadata].includes(criteria.type@@ -118,8 +131,8 @@ function processCohortCriteria(criteria: AnyCohortCriteriaType): AnyCohortCriterif ([BehavioralFilterKey.Behavioral].includes(criteria.type) &&!('explicit_datetime' in criteria) &&- criteria.value &&- COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME.includes(criteria.value)+ processedCriteria.value &&+ COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME.includes(processedCriteria.value)) {processedCriteria.explicit_datetime = convertTimeValueToRelativeTime(criteria)}diff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsxindex 2f97801b52f1..677a615bd8ff 100644--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx@@ -613,10 +613,10 @@ describe('cohortEditLogic', () => {cleanup()})- it('renders the editor instead of crashing when a criterion has a value with no ROWS entry', async () => {- // Stored criteria can carry a behavioral value with no ROWS entry, which the row builder- // still has to render. A throw here replaces the whole scene with the error boundary, so- // finding the cohort name is what proves the criteria row rendered.+ // Stored criteria can carry a behavioral value with no ROWS entry. Values that instead+ // resolve to an Object.prototype member are covered against getRowShape in cohortUtils.test,+ // since this scene render is the most expensive place to assert the same lookup.+ it('renders an empty, recoverable criteria row for an unmapped value', async () => {const cohortId = 11useMocks({@@ -654,7 +654,17 @@ describe('cohortEditLogic', () => {render(<CohortEdit id={cohortId} />)+ // The name only gates on the cohort having loaded; a throw in the row builder has no+ // error boundary between here and the test, so it fails the render outright.expect(await screen.findByText('Unmapped Criteria Cohort')).toBeInTheDocument()+ expect(document.querySelector('.CohortCriteriaRow')).toBeInTheDocument()+ expect(screen.getByText('Choose criterion')).toBeInTheDocument()+ // Counting fields is what catches a revert to the PerformEvent fallback: the stored+ // key would label the event picker rather than leave its placeholder visible, so the+ // placeholder assertion above would still pass.+ expect(document.querySelectorAll('.CohortCriteriaRow__Criteria__Field')).toHaveLength(1)+ expect(document.querySelector('.CohortCriteriaRow__Criteria__arrow')).not.toBeInTheDocument()+ expect(screen.getByText("This criterion isn't valid. Choose a new one to replace it.")).toBeInTheDocument()})})})diff --git a/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx b/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsxindex 9ef4a6fb8f75..ed64f7cf31d3 100644--- a/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx+++ b/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx@@ -10,7 +10,7 @@ import { LemonDivider } from '@posthog/lemon-ui'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { CohortLogicProps, cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'-import { ROWS, renderField } from 'scenes/cohorts/CohortFilters/constants'+import { getRowShape, renderField } from 'scenes/cohorts/CohortFilters/constants'import { BehavioralFilterType, CohortFieldProps, Field, FilterType } from 'scenes/cohorts/CohortFilters/types'import { cleanCriteria } from 'scenes/cohorts/cohortUtils'@@ -37,10 +37,11 @@ export function CohortCriteriaRowBuilder({onChangeType,}: CohortCriteriaRowBuilderProps): JSX.Element {const { setCriteria, duplicateFilter, removeFilter } = useActions(cohortEditLogic)- // Stored criteria can carry a behavioral value that isn't a known ROWS key (legacy or- // otherwise unmapped). Fall back to the default event row so the cohort still renders and- // stays editable instead of throwing when we later read rowShape.fields.- const rowShape = ROWS[type] ?? ROWS[BehavioralEventType.PerformEvent]+ // Falling back to another row's fields would let an edit merge into the unmapped criterion,+ // which cleanCriteria then strips to undefined. An empty row keeps the type selector as the+ // recovery path.+ const rowShape = getRowShape(type)+ const rowFields = rowShape?.fields ?? []const renderFieldComponent = (_field: Field, i: number): JSX.Element => {return (@@ -107,6 +108,7 @@ export function CohortCriteriaRowBuilder({{renderField[FilterType.Behavioral]({fieldKey: 'value',criteria,+ placeholder: 'Choose criterion',onChange: (newCriteria) => {setCriteria(cleanCriteria(newCriteria, true), groupIndex, index)onChangeType?.(newCriteria['value'] ?? BehavioralEventType.PerformEvent)@@ -121,42 +123,50 @@ export function CohortCriteriaRowBuilder({<LemonButton icon={<IconTrash />} onClick={() => removeFilter(groupIndex, index)} />)}</div>- <div className="flex">- <span className="CohortCriteriaRow__Criteria__arrow">↳</span>- <div className="flex flex-wrap items-center min-w-0">- {rowShape.fields.map((field, i) => {- return (- !field.hide &&- (field.fieldKey ? (- <KeaField- key={i}- name={field.fieldKey}- template={({ error, kids }) => {- return (- <>- <div- className={clsx(- 'CohortCriteriaRow__Criteria__Field',- error && `CohortCriteriaRow__Criteria__Field--error`- )}- >- {kids as React.ReactNode}- </div>- </>- )- }}- >- <>{renderFieldComponent(field, i)}</>- </KeaField>- ) : (- <div key={i} className="CohortCriteriaRow__Criteria__Field">- {renderFieldComponent(field, i)}- </div>- ))- )- })}+ {!rowShape && (+ <LemonBanner className="my-2" type="warning">+ This criterion isn't valid. Choose a new one to replace it.+ </LemonBanner>+ )}+ {/* The arrow points at the fields, so it has nothing to point at on an empty row. */}+ {rowFields.length > 0 && (+ <div className="flex">+ <span className="CohortCriteriaRow__Criteria__arrow">↳</span>+ <div className="flex flex-wrap items-center min-w-0">+ {rowFields.map((field, i) => {+ return (+ !field.hide &&+ (field.fieldKey ? (+ <KeaField+ key={i}+ name={field.fieldKey}+ template={({ error, kids }) => {+ return (+ <>+ <div+ className={clsx(+ 'CohortCriteriaRow__Criteria__Field',+ error && `CohortCriteriaRow__Criteria__Field--error`+ )}+ >+ {kids as React.ReactNode}+ </div>+ </>+ )+ }}+ >+ <>{renderFieldComponent(field, i)}</>+ </KeaField>+ ) : (+ <div key={i} className="CohortCriteriaRow__Criteria__Field">+ {renderFieldComponent(field, i)}+ </div>+ ))+ )+ })}+ </div></div>- </div>+ )}</></KeaField></div>diff --git a/frontend/src/scenes/cohorts/CohortFilters/constants.tsx b/frontend/src/scenes/cohorts/CohortFilters/constants.tsxindex b58a46ebc176..f4e8a711f89a 100644--- a/frontend/src/scenes/cohorts/CohortFilters/constants.tsx+++ b/frontend/src/scenes/cohorts/CohortFilters/constants.tsx@@ -907,6 +907,13 @@ export const ROWS: Record<BehavioralFilterType, Row> = {},}+// Stored criteria can carry any string as their behavioral value, including keys inherited from+// Object.prototype ('constructor', 'toString', ...) that a plain `ROWS[type]` lookup resolves to a+// truthy non-row. Every read of ROWS by criteria value must go through here.+export function getRowShape(type: BehavioralFilterType): Row | undefined {+ return Object.hasOwn(ROWS, type) ? ROWS[type] : undefined+}+export const COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME = Object.entries(ROWS).filter(([_, row]) => row.fields.some((field) => field.type === FilterType.RelativeAndExactTime)).map(([eventType, _]) => eventType)diff --git a/frontend/src/scenes/cohorts/cohortUtils.test.tsx b/frontend/src/scenes/cohorts/cohortUtils.test.tsxindex 4a2691b8294a..8c0b6df6e35f 100644--- a/frontend/src/scenes/cohorts/cohortUtils.test.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.test.tsx@@ -1,6 +1,12 @@import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { BehavioralFilterKey, CohortClientErrors } from 'scenes/cohorts/CohortFilters/types'-import { cleanBehavioralTypeCriteria, determineFilterType, validateGroup } from 'scenes/cohorts/cohortUtils'+import {+ cleanBehavioralTypeCriteria,+ cleanCriteria,+ criteriaToHumanSentence,+ determineFilterType,+ validateGroup,+} from 'scenes/cohorts/cohortUtils'import { AnyCohortCriteriaType, BehavioralEventType, CohortCriteriaGroupFilter, FilterLogicalOperator } from '~/types'@@ -201,3 +207,25 @@ describe('cleanBehavioralTypeCriteria', () => {expect(cleanBehavioralTypeCriteria(criteria).type).toBe(BehavioralFilterKey.Person)})})++describe('criteria whose value collides with an Object.prototype key', () => {+ // The API stores `value` as an unconstrained string, so keys like `constructor` can reach the+ // client. A plain ROWS lookup resolves those to a truthy non-row, which slips past both+ // functions' missing-row guards and then throws on the `fields` access behind them.+ const criteria = (value: string): AnyCohortCriteriaType => ({+ type: BehavioralFilterKey.Behavioral,+ value: value as BehavioralEventType,+ key: '$pageview',+ })++ it.each([['constructor'], ['toString'], ['__proto__']])('cleanCriteria empties the criterion for %s', (value) => {+ expect(cleanCriteria(criteria(value))).toEqual({ type: undefined, value: undefined, negation: false })+ })++ it.each([['constructor'], ['toString'], ['__proto__']])(+ 'criteriaToHumanSentence renders nothing for %s',+ (value) => {+ expect(criteriaToHumanSentence(criteria(value), {}, {})).toEqual(<></>)+ }+ )+})diff --git a/frontend/src/scenes/cohorts/cohortUtils.tsx b/frontend/src/scenes/cohorts/cohortUtils.tsxindex d7ffce019de0..6b99ab3f9bcc 100644--- a/frontend/src/scenes/cohorts/cohortUtils.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.tsx@@ -7,7 +7,7 @@ import { ENTITY_MATCH_TYPE, PROPERTY_MATCH_TYPE } from 'lib/constants'import { calculateDays } from 'lib/utils/durations'import { isNumeric } from 'lib/utils/guards'import { areObjectValuesEmpty } from 'lib/utils/objects'-import { BEHAVIORAL_TYPE_TO_LABEL, CRITERIA_VALIDATIONS, ROWS } from 'scenes/cohorts/CohortFilters/constants'+import { BEHAVIORAL_TYPE_TO_LABEL, CRITERIA_VALIDATIONS, getRowShape } from 'scenes/cohorts/CohortFilters/constants'import {BehavioralFilterKey,BehavioralFilterType,@@ -374,7 +374,7 @@ export function validateGroup(return {values: criteria.map((c) => {const behavioralFilterType = criteriaToBehavioralFilterType(c)- const row = ROWS[behavioralFilterType]+ const row = getRowShape(behavioralFilterType)let requiredFields = (row?.fields ?? []).filter((f) => !!f.fieldKey) as FieldWithFieldKey[]// Edge case where property value is not required if operator is "is set" or "is not set"@@ -603,7 +603,7 @@ function getCriteriaValue(criteria: AnyCohortCriteriaType, key: string): any {// Populate empty values with default values on changing type, pruning any extra variablesexport function cleanCriteria(criteria: AnyCohortCriteriaType, shouldPurge: boolean = false): AnyCohortCriteriaType {const populatedCriteria: Record<string, any> = {}- const { fields, ...apiProps } = ROWS[criteriaToBehavioralFilterType(criteria)] ?? { fields: [] }+ const { fields, ...apiProps } = getRowShape(criteriaToBehavioralFilterType(criteria)) ?? { fields: [] }Object.entries(apiProps).forEach(([key, defaultValue]) => {const nextValue = getCriteriaValue(criteria, key) ?? defaultValueif (shouldPurge) {@@ -639,7 +639,7 @@ export function criteriaToHumanSentence(actionsById: Partial<Record<string | number, ActionType>>): React.ReactNode {const words: React.ReactNode[] = []- const data = ROWS[criteriaToBehavioralFilterType(criteria)]+ const data = getRowShape(criteriaToBehavioralFilterType(criteria))if (!data) {return <></>diff --git a/posthog/models/property/property.py b/posthog/models/property/property.pyindex 02af33ba9bbe..5a175eabd081 100644--- a/posthog/models/property/property.py+++ b/posthog/models/property/property.py@@ -157,6 +157,8 @@ VALIDATE_CONDITIONAL_BEHAVIORAL_PROP_TYPES = {],}+# Mirrored in frontend/src/models/cohortsModel.ts (BEHAVIORAL_VALUE_ALIASES) so the cohort+# editor renders an aliased criterion rather than flagging it as invalid. Add to both.# Behavioral `value`s that don't match BehavioralPropertyType's enum value but are# produced by cohort filter generators and are equivalent for validation purposes.# Keyed by the raw stored value string; resolves to the canonical type whose