: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
import { Fragment } from 'react'
import {
describeListChanges,
describeTagChanges,
} from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'
import { describeChangeMappings } from 'lib/components/ActivityLog/activityDescriptions/describeChangeMappings'
import {
ActivityChange,
ActivityLogItem,
Describer,
ActivityLogUserName,
ChangeMapping,
Description,
ExpandedView,
HumanizedChange,
activityLogSummary,
defaultDescriber,
detectBoolean,
} from 'lib/components/ActivityLog/humanizeActivity'
import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
import { PropertyFilterButton } from 'lib/components/PropertyFilters/components/PropertyFilterButton'
import { Link } from 'lib/lemon-ui/Link'
import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { FeatureFlagEvaluationRuntime, FeatureFlagFilters, FeatureFlagGroupType, FeatureFlagType } from '~/types'
import { FeatureFlagReleaseConditionsChange } from 'products/feature_flags/frontend/FeatureFlagReleaseConditionsChange'
import {
ConditionSetAspect,
ConditionSetChange,
changedAspects,
diffReleaseConditionSets,
rolloutOf,
} from 'products/feature_flags/frontend/releaseConditionsDiff'
const getChangedPayloadKeys = (
filtersBefore: FeatureFlagFilters | undefined,
filtersAfter: FeatureFlagFilters
): string[] =>
Object.keys(filtersAfter.payloads ?? {}).filter((key) => {
const before = filtersBefore?.payloads?.[key]?.toString() || null
const after = filtersAfter.payloads?.[key]?.toString() || null
return before !== after
})
const nameOrLinkToFlag = (id: string | undefined, name: string | null | undefined): string | JSX.Element => {
const displayName = name || '(empty string)'
return id ? <Link to={urls.featureFlag(id)}>{displayName}</Link> : displayName
}
const getRuntimeLabel = (runtime: string): string => {
switch (runtime) {
case FeatureFlagEvaluationRuntime.ALL:
return 'both client and server'
case FeatureFlagEvaluationRuntime.CLIENT:
return 'client-side only'
case FeatureFlagEvaluationRuntime.SERVER:
return 'server-side only'
default:
return runtime
}
}
const rolloutLabel = (rollout: number): JSX.Element => <strong className="tabular-nums">{rollout}%</strong>
const conditionSetLabel = (group: FeatureFlagGroupType): JSX.Element => {
if (group.description) {
return <strong>"{group.description}"</strong>
}
const properties = group.properties ?? []
if (properties.length === 0) {
return <strong>{group.aggregation_group_type_index != null ? 'all groups' : 'all users'}</strong>
}
return (
<>
<PropertyFilterButton item={properties[0]} />
{properties.length > 1 && (
<span className="text-muted">
{' '}
and {properties.length - 1} more{' '}
{pluralize(properties.length - 1, 'condition', 'conditions', false)}
</span>
)}
</>
)
}
const joinInline = (parts: JSX.Element[]): JSX.Element => (
<>
{parts.map((part, index) => (
<Fragment key={index}>
{index > 0 && (index === parts.length - 1 ? ' and ' : ', ')}
{part}
</Fragment>
))}
</>
)
const conditionSetsNoun = (count: number): string => pluralize(count, 'condition set', 'condition sets')
const MAX_DETAILED_SET_CHANGES = 3
// Description comes last because it only ever reads as a tail: "... and its description".
const DESCRIBED_ASPECTS: ConditionSetAspect[] = ['criteria', 'rollout', 'variant', 'description']
const describedAspects = (set: ConditionSetChange): ConditionSetAspect[] => {
const aspects = changedAspects(set)
return DESCRIBED_ASPECTS.filter((aspect) => aspects.includes(aspect))
}
const rolloutChangeFragment = (set: ConditionSetChange): JSX.Element => (
<>
from {rolloutLabel(rolloutOf(set.previous ?? set.group))} to {rolloutLabel(rolloutOf(set.group))}
</>
)
const variantChangeFragment = (set: ConditionSetChange): JSX.Element => (
<>
from <strong>{set.previous?.variant ?? 'none'}</strong> to <strong>{set.group.variant ?? 'none'}</strong>
</>
)
interface AspectWording {
verb: string
noun: string
subject: (set: ConditionSetChange) => JSX.Element
fragment?: (set: ConditionSetChange) => JSX.Element
}
// A description change names its set by position, because the label of a set is its description.
const ASPECT_WORDING: Record<ConditionSetAspect, AspectWording> = {
criteria: {
verb: 'changed the criteria for',
noun: 'criteria',
subject: (set) => conditionSetLabel(set.group),
},
rollout: {
verb: 'changed the rollout for',
noun: 'rollout',
subject: (set) => conditionSetLabel(set.group),
fragment: rolloutChangeFragment,
},
variant: {
verb: 'changed the variant for',
noun: 'variant',
subject: (set) => conditionSetLabel(set.group),
fragment: variantChangeFragment,
},
description: {
verb: 'changed the description of',
noun: 'description',
subject: (set) => <>condition set {set.index + 1}</>,
},
}
const aspectDetail = (set: ConditionSetChange, aspect: ConditionSetAspect): JSX.Element => {
const { subject, fragment } = ASPECT_WORDING[aspect]
return fragment ? (
<>
{subject(set)} {fragment(set)}
</>
) : (
subject(set)
)
}
const aspectHeadClause = (set: ConditionSetChange, aspect: ConditionSetAspect): JSX.Element => (
<>
{ASPECT_WORDING[aspect].verb} {aspectDetail(set, aspect)}
</>
)
const aspectTailClause = (set: ConditionSetChange, aspect: ConditionSetAspect): JSX.Element => {
const { noun, fragment } = ASPECT_WORDING[aspect]
return fragment ? (
<>
its {noun} {fragment(set)}
</>
) : (
<>its {noun}</>
)
}
const conditionSetClause = (set: ConditionSetChange): JSX.Element => {
const [head, ...rest] = describedAspects(set)
return joinInline([aspectHeadClause(set, head), ...rest.map((aspect) => aspectTailClause(set, aspect))])
}
const describeConditionSetChanges = (
filtersBefore: FeatureFlagFilters | undefined,
filtersAfter: FeatureFlagFilters
): Description[] => {
const diff = diffReleaseConditionSets(filtersBefore, filtersAfter)
const added = diff.sets.filter((set) => set.status === 'added')
const changed = diff.sets.filter((set) => set.status === 'changed')
const summarize = added.length + changed.length + diff.removed.length > MAX_DETAILED_SET_CHANGES
// A set that changed in more than one way reads better as a single clause than as an entry in
// each per-aspect list, where its label would repeat. Counts have no label to repeat.
const multiAspect: ConditionSetChange[] = summarize ? [] : changed.filter((set) => describedAspects(set).length > 1)
const withAspect = (aspect: ConditionSetAspect): ConditionSetChange[] =>
changed.filter((set) => !multiAspect.includes(set) && changedAspects(set).includes(aspect))
// Past the detail limit every part collapses to "<verb> N condition sets"; the expanded view has the rest.
const listOrCount = (
sets: ConditionSetChange[],
verbs: { detail: string; count?: string },
detail: (set: ConditionSetChange) => JSX.Element
): JSX.Element =>
summarize ? (
<>
{verbs.count ?? verbs.detail} {conditionSetsNoun(sets.length)}
</>
) : (
<>
{verbs.detail} {joinInline(sets.map(detail))}
</>
)
const labelOf = (set: ConditionSetChange): JSX.Element => conditionSetLabel(set.group)
const parts: Description[] = []
DESCRIBED_ASPECTS.forEach((aspect) => {
const sets = withAspect(aspect)
if (sets.length) {
parts.push(listOrCount(sets, { detail: ASPECT_WORDING[aspect].verb }, (set) => aspectDetail(set, aspect)))
}
})
parts.push(...multiAspect.map(conditionSetClause))
if (added.length) {
const verbs = {
detail: added.length === 1 ? 'added a condition set for' : 'added condition sets for',
count: 'added',
}
parts.push(
listOrCount(added, verbs, (set) => (
<>
{labelOf(set)} at {rolloutLabel(rolloutOf(set.group))}
</>
))
)
}
if (diff.removed.length) {
parts.push(
diff.removed.length === 1 && !summarize ? (
<>removed the condition set for {conditionSetLabel(diff.removed[0].group)}</>
) : (
<>removed {conditionSetsNoun(diff.removed.length)}</>
)
)
}
if (diff.reordered) {
parts.push(<>reordered the condition sets</>)
}
return parts
}
// Shared handler for fields the feed deliberately never describes. EXCLUDED_FLAG_FIELDS is
// derived by identity from this function, so excluded fields stay distinguishable from
// describable fields whose handler returned null for one particular change.
const excludedFieldHandler = (): null => null
const featureFlagActionsMapping: Record<
keyof FeatureFlagType,
(change?: ActivityChange, logItem?: ActivityLogItem) => ChangeMapping | null
> = {
name: function onName(change) {
return {
description: [<>changed the description</>],
preview: typeof change?.after === 'string' ? change.after : undefined,
}
},
active: function onActive(change, logItem) {
let isActive: boolean = !!change?.after
if (typeof change?.after === 'string') {
isActive = change?.after.toLowerCase() === 'true'
}
const describeChange: string = isActive ? 'enabled' : 'disabled'
return {
description: [<>{describeChange}</>],
suffix: <>{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}</>,
}
},
filters: function onChangedFilter(change, logItem) {
const filtersBefore = change?.before as FeatureFlagFilters | undefined
const filtersAfter = change?.after as FeatureFlagFilters
const hasConditionSets = Array.isArray(filtersAfter?.groups)
// A flag left with an empty variants list is a boolean flag again, so its payload is the
// boolean one. Reading the whole `multivariate` object here would leave that payload undescribed.
const isMultivariateFlag = !!filtersAfter?.multivariate?.variants?.length
const changes: Description[] = []
let expandedView: ExpandedView | undefined
if (hasConditionSets) {
if (!isMultivariateFlag) {
getChangedPayloadKeys(filtersBefore, filtersAfter).forEach((key) => {
const changedPayload = filtersAfter.payloads?.[key]?.toString() || null
changes.push(<SentenceList listParts={[changedPayload]} prefix="changed payload to" />)
})
}
const setChanges = describeConditionSetChanges(filtersBefore, filtersAfter)
changes.push(...setChanges)
if (setChanges.length > 0) {
// The expanded view tags what moved between the two condition set lists, so it has
// nothing to show for a save that left them alone.
expandedView = {
label: 'Release conditions',
content: (
<FeatureFlagReleaseConditionsChange
flagId={logItem?.item_id ?? ''}
activityId={logItem?.id ?? logItem?.created_at ?? ''}
before={filtersBefore}
after={filtersAfter}
/>
),
}
}
}
if (filtersBefore?.multivariate?.variants?.length && !filtersAfter?.multivariate?.variants?.length) {
changes.push(
<SentenceList
key="remove-variants-list"
listParts={[
<span key="remove-variants">
removed{' '}
{filtersBefore.multivariate.variants.length === 1 ? 'the last variant' : 'all variants'}
</span>,
]}
/>
)
} else if (isMultivariateFlag) {
getChangedPayloadKeys(filtersBefore, filtersAfter).forEach((key) => {
const changedPayload = filtersAfter.payloads?.[key]?.toString() || null
changes.push(
<SentenceList
listParts={[
<span key={key} className="highlighted-activity">
{changedPayload}
</span>,
]}
prefix={
<span>
changed payload on <b>variant: {key}</b> to
</span>
}
/>
)
})
// Identify removed variants
const beforeVariants = new Set((filtersBefore?.multivariate?.variants || []).map((v) => v.key))
const afterVariants = new Set((filtersAfter?.multivariate?.variants || []).map((v) => v.key))
const removedVariants = [...beforeVariants].filter((key) => !afterVariants.has(key))
// Only show rollout percentage changes if they actually changed
const beforeVariantMap = new Map(
(filtersBefore?.multivariate?.variants || []).map((v) => [v.key, v.rollout_percentage])
)
const changedVariants = (filtersAfter.multivariate?.variants || []).filter(
(v) => beforeVariantMap.get(v.key) !== v.rollout_percentage
)
if (changedVariants.length > 0) {
changes.push(
<SentenceList
listParts={changedVariants.map((v) => (
<div key={v.key} className="highlighted-activity">
{v.key}: <strong className="tabular-nums">{v.rollout_percentage}%</strong>
</div>
))}
prefix="changed the rollout percentage for the variants to"
/>
)
}
// Then add removed variants if any
if (removedVariants.length > 0) {
changes.push(
<SentenceList
listParts={removedVariants.map((key) => (
<span key={key} className="highlighted-activity">
<strong>{key}</strong>
</span>
))}
prefix={`removed ${pluralize(
removedVariants.length,
'variant',
undefined,
/* includeNumber: */ false
)}`}
/>
)
}
}
if (changes.length > 0) {
return { description: changes, expandedView }
}
console.error({ change }, 'could not describe this change')
return null
},
deleted: function onSoftDelete(change, logItem) {
const isDeleted = detectBoolean(change?.after)
return {
description: [<>{isDeleted ? 'deleted' : 'restored'}</>],
suffix: <>{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}</>,
}
},
archived: function onArchived(change, logItem) {
const isArchived = detectBoolean(change?.after)
return {
description: [<>{isArchived ? 'archived' : 'unarchived'}</>],
suffix: <>{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}</>,
}
},
key: function onKey(change, logItem) {
const changeBefore = change?.before as string
const changeAfter = change?.after as string
return {
description: [<>changed flag key on {changeBefore} to</>],
summary: [
<>
Changed the flag key from {changeBefore} to {changeAfter}
</>,
],
suffix: <>{nameOrLinkToFlag(logItem?.item_id, changeAfter)}</>,
}
},
ensure_experience_continuity: function onExperienceContinuity(change) {
const isEnabled = detectBoolean(change?.after)
const describeChange: string = isEnabled ? 'enabled' : 'disabled'
return { description: [<>{describeChange} experience continuity</>] }
},
evaluation_runtime: function onEvaluationRuntime(change) {
const runtimeAfter = change?.after as string
const runtimeBefore = change?.before as string
return {
description: [
<>
changed the evaluation runtime from <strong>{getRuntimeLabel(runtimeBefore)}</strong> to{' '}
<strong>{getRuntimeLabel(runtimeAfter)}</strong>
</>,
],
}
},
bucketing_identifier: function onBucketingIdentifier(change) {
const identifierAfter = change?.after as string
const identifierBefore = change?.before as string
const getBucketingLabel = (identifier: string): string => {
switch (identifier) {
case 'distinct_id':
return 'User'
case 'device_id':
return 'Device'
default:
return identifier || 'User'
}
}
return {
description: [
<>
changed the bucketing identifier from <strong>{getBucketingLabel(identifierBefore)}</strong> to{' '}
<strong>{getBucketingLabel(identifierAfter)}</strong>
</>,
],
}
},
tags: describeTagChanges,
evaluation_contexts: (change) => describeListChanges(change, 'evaluation context', 'evaluation contexts'),
// fields that are excluded on the backend
id: excludedFieldHandler,
created_at: excludedFieldHandler,
created_by: excludedFieldHandler,
updated_at: excludedFieldHandler,
experiment_set: excludedFieldHandler,
experiment_set_metadata: excludedFieldHandler,
features: excludedFieldHandler,
usage_dashboard: excludedFieldHandler,
can_edit: excludedFieldHandler,
has_enriched_analytics: excludedFieldHandler,
surveys: excludedFieldHandler,
user_access_level: excludedFieldHandler,
is_remote_configuration: excludedFieldHandler,
has_encrypted_payloads: excludedFieldHandler,
status: excludedFieldHandler,
version: excludedFieldHandler,
last_modified_by: excludedFieldHandler,
last_called_at: excludedFieldHandler,
is_used_in_replay_settings: excludedFieldHandler,
_create_in_folder: excludedFieldHandler,
}
const EXCLUDED_FLAG_FIELDS = new Set(
Object.keys(featureFlagActionsMapping).filter(
(field) => featureFlagActionsMapping[field as keyof FeatureFlagType] === excludedFieldHandler
)
)
const getActorName = (logItem: ActivityLogItem): JSX.Element => {
if (logItem.detail.trigger?.job_type === 'scheduled_change') {
return (
<>
<ActivityLogUserName logItem={logItem} /> <span className="text-muted">(via scheduled change)</span>
</>
)
}
return <ActivityLogUserName logItem={logItem} />
}
// A referenced cohort's conditions changed: the flag's own fields are untouched
// (only its version moved), so describe the cohort change instead of a field diff.
// job_type must stay in sync with COHORT_CONDITIONS_UPDATED_JOB_TYPE in
// products/feature_flags/backend/flag_version_sync.py.
function describeLinkedCohortUpdate(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
const { cohort_id, cohort_name } = logItem.detail.trigger?.payload ?? {}
return {
summary: activityLogSummary(
logItem,
<>
Changed the conditions of linked cohort{' '}
{cohort_id ? (
<Link to={urls.cohort(cohort_id)}>{cohort_name || `#${cohort_id}`}</Link>
) : (
cohort_name || 'unknown'
)}
</>,
nameOrLinkToFlag(logItem.item_id, logItem.detail.name),
undefined,
getActorName(logItem)
),
description: (
<SentenceList
listParts={[
<Fragment key="cohort-conditions-updated">
changed the conditions of linked cohort{' '}
{cohort_id ? (
<Link to={urls.cohort(cohort_id)}>{cohort_name || `#${cohort_id}`}</Link>
) : (
<span>{cohort_name || 'unknown'}</span>
)}
</Fragment>,
]}
prefix={getActorName(logItem)}
suffix={
<>
on {asNotification && ' the flag '}
{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}
</>
}
/>
),
}
}
// A flag this one depends on changed its definition: same story as above, only
// this flag's version moved. job_type must stay in sync with
// FLAG_DEPENDENCY_UPDATED_JOB_TYPE in
// products/feature_flags/backend/flag_version_sync.py.
function describeLinkedFlagUpdate(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
const { flag_id, flag_key } = logItem.detail.trigger?.payload ?? {}
return {
summary: activityLogSummary(
logItem,
<>
Changed the definition of linked flag{' '}
{flag_id ? (
<Link to={urls.featureFlag(flag_id)}>{flag_key || `#${flag_id}`}</Link>
) : (
flag_key || 'unknown'
)}
</>,
nameOrLinkToFlag(logItem.item_id, logItem.detail.name),
undefined,
getActorName(logItem)
),
description: (
<SentenceList
listParts={[
<Fragment key="flag-dependency-updated">
changed the definition of linked flag{' '}
{flag_id ? (
<Link to={urls.featureFlag(flag_id)}>{flag_key || `#${flag_id}`}</Link>
) : (
<span>{flag_key || 'unknown'}</span>
)}
</Fragment>,
]}
prefix={getActorName(logItem)}
suffix={
<>
on {asNotification && ' the flag '}
{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}
</>
}
/>
),
}
}
// The experiment exposure freeze rewrites the flag's filters to pin enrollment to a
// snapshot cohort; without the trigger check the rewrite reads as a manual targeting
// edit. job_type must stay in sync with the Trigger in
// products/experiments/backend/experiment_service.py.
function describeExposureFrozen(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
return {
summary: activityLogSummary(
logItem,
'Restricted the release conditions to the exposure freeze snapshot cohort',
nameOrLinkToFlag(logItem.item_id, logItem.detail.name),
undefined,
getActorName(logItem)
),
description: (
<SentenceList
listParts={['restricted the release conditions to the exposure freeze snapshot cohort']}
prefix={getActorName(logItem)}
suffix={
<>
on {asNotification && ' the flag '}
{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}
</>
}
/>
),
}
}
function describeExposureUnfrozen(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
return {
summary: activityLogSummary(
logItem,
'Removed the exposure freeze restriction',
nameOrLinkToFlag(logItem.item_id, logItem.detail.name),
undefined,
getActorName(logItem)
),
description: (
<SentenceList
listParts={['removed the exposure freeze restriction']}
prefix={getActorName(logItem)}
suffix={
<>
from {asNotification && ' the flag '}
{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}
</>
}
/>
),
}
}
const FLAG_TRIGGER_DESCRIBERS = new Map<string, Describer>([
['cohort_conditions_updated', describeLinkedCohortUpdate],
['flag_dependency_updated', describeLinkedFlagUpdate],
['experiment_exposure_frozen', describeExposureFrozen],
['experiment_exposure_unfrozen', describeExposureUnfrozen],
])
function describeFlagFieldChanges(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange | null {
const mappings: ChangeMapping[] = []
for (const change of logItem.detail.changes || []) {
if (!change?.field) {
continue
}
const handler = featureFlagActionsMapping[change.field as keyof FeatureFlagType]
if (!handler) {
console.error({ field: change.field, change }, 'No activity describer found for feature flag field')
}
const result = handler ? handler(change, logItem) : null
if (result) {
mappings.push(result)
}
}
return describeChangeMappings(
logItem,
mappings,
nameOrLinkToFlag(logItem.item_id, logItem.detail.name),
<>
on {asNotification && ' the flag '}
{nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}
</>,
getActorName(logItem)
)
}
export function flagActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
if (logItem.scope != 'FeatureFlag') {
console.error('feature flag describer received a non-feature flag activity')
return { description: null }
}
if (logItem.activity === 'created') {
return {
summary: activityLogSummary(
logItem,
'Created the feature flag',
nameOrLinkToFlag(logItem.item_id, logItem.detail.name),
undefined,
getActorName(logItem)
),
description: (
<SentenceList
listParts={[<>created a new feature flag:</>]}
prefix={getActorName(logItem)}
suffix={<> {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}</>}
/>
),
}
}
if (logItem.activity == 'updated') {
const describeTrigger = FLAG_TRIGGER_DESCRIBERS.get(logItem.detail.trigger?.job_type ?? '')
if (describeTrigger) {
return describeTrigger(logItem, asNotification)
}
const changes = describeFlagFieldChanges(logItem, asNotification)
if (changes) {
return changes
}
const updateChanges = logItem.detail.changes || []
if (
updateChanges.length > 0 &&
updateChanges.every((change) => change.field && EXCLUDED_FLAG_FIELDS.has(change.field))
) {
// Every change is to an excluded field, which happens when a save only bumps the
// optimistic-concurrency `version`. The fallback would render a contentless
// "updated <flag>" row, so drop the entry instead. A describable change whose
// handler produced no text still falls through to the generic fallback.
return { description: null }
}
}
return defaultDescriber(logItem, asNotification, nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name))
}