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.

feat(cohorts): show whether feature flags can target a cohort (#101256)

Matheus Batista9f8cd0dff4cd
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a89fa3c1765f..7e80e882780e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2932,6 +2932,10 @@ snapshots:
hash: v1.k794b7964.39915d4d2e7941a192598711dc078f8412927946a2174ceb6fa9137db0bcd39d.Ij-VXWTXnTqi38Y4Fdxxvhi1l3g4tqV80rRWIrAWehM
filters-taxonomic-filter--category-rail-pinned--light:
hash: v1.k794b7964.dd22935d8d4ebf873b40796ee98c8e3e733752cd759ae26305c3b542d692c0f6.rlGfkU84C0KPwFL_PxWf4NYBsDwQUjkaL-ZzdtcBjZU
+ filters-taxonomic-filter--cohorts-with-realtime-states--dark:
+ hash: v1.k794b7964.4ecf5ef9bc95151a6444f1b7247ced4f43ad62f12399783f180c8d82f2b05021.12FrJN6IzU1RbrsFSt_QSvWv4xtr7haSiCTFtyE4ks4
+ filters-taxonomic-filter--cohorts-with-realtime-states--light:
+ hash: v1.k794b7964.c31271e138b12e3328be8e2cfb274debb8e9f0962628bf7fade105700d643279.AtCH44-aoOKmp6KdEobKIZ3sTK751wyBALto1doHhZc
filters-taxonomic-filter--dashboard-property-search--dark:
hash: v1.k794b7964.c824be157968e0ef1b8dc82810f4a06dfff364af71722c53823f1d95d4542f7f.D-ZfI3CwGqAa9tdEaUF_psLO6gqWhGZTQnN6Y9i8GRY
filters-taxonomic-filter--dashboard-property-search--light:
@@ -3004,6 +3008,10 @@ snapshots:
hash: v1.k794b7964.4cfbb81c4c750a1ce92af203b15f88591898401a3627a4bcd6cb953896cfa101.AYKwPfqIFp6iTqcfHtoWTb1DLwMxhhNPcILKsS2-YoY
filters-taxonomic-filter--three-groups-default-layout--light:
hash: v1.k794b7964.52b14938c6d46ada7a2e836ffb42d822b5fdb110021929729fef734f80fa0c3c.c7Ny9VfNlpKbolYt_jxLFlxHU0SgbWywGVLn4XdpU5M
+ filters-taxonomic-filter-menu-rebuild--cohorts-with-realtime-states--dark:
+ hash: v1.k794b7964.932df90594833f5d2039f583a662cc2aa42e72c7ad7f13f3075bd06a0119d077.O-c_P7j4v0FdBkmPUMcU5gjN-BPns7MvdvhkXEGQxcE
+ filters-taxonomic-filter-menu-rebuild--cohorts-with-realtime-states--light:
+ hash: v1.k794b7964.fe2e8e9e5341a9f15b78620d2fed44cd829a0dfb29249d4c72809fd91295f87a.K0E_-NAOF_HgRwpV5XJvo2HvQhUqCKwQTIwbWJfw2KQ
filters-taxonomic-filter-menu-rebuild--data-warehouse-config--dark:
hash: v1.k794b7964.65d09fee9c238c115968cf8d58095e4a6475df3ab2b17ef749dd95fb3e59d891.W1yXgDjU4S7qUSNq-keATF_yBgPjnJL4ORrSnK7hlGg
filters-taxonomic-filter-menu-rebuild--data-warehouse-config--light:
@@ -7952,6 +7960,10 @@ snapshots:
hash: v1.k794b7964.e1dfb6468ff74a889420d45ecbc302f87a626d673e0ef9c64cbfbecdace26b2b.wSp5r_2D3wYHqnlyaV8kJdqyiB1-q4TCCNbThYjT73g
scenes-app-feature-flags--edit-feature-flag--light:
hash: v1.k794b7964.90374223e2bdbd8a35bdd122980abe5aa9c4c05492b05af5cfb74b0a03935504.KajqIAXC6pPw_S9XS1K42YrVKND36xFXF3xpjaUcb2U
+ scenes-app-feature-flags--edit-feature-flag-conditions-with-realtime-cohort--dark:
+ hash: v1.k794b7964.6d903d196d01796d19b48cba0b83dce14c823016ca379c65173ec082ab6a9098.AJvpm1rTKagKFx4x8KZs6gph_XUb2-FEhkOHR1EGMfw
+ scenes-app-feature-flags--edit-feature-flag-conditions-with-realtime-cohort--light:
+ hash: v1.k794b7964.6b1f0a4db8510394fbaef42ea4766eb3a4aec80ee3c06cca3dd575c4170c82f8._tSTLZIzXv48PugUZhC5d6EYA2thGLS2WybkiGn3pEA
scenes-app-feature-flags--edit-multi-variate-feature-flag--dark:
hash: v1.k794b7964.aef599e63804182147ff502c895f17258da74e1a09f28462838bd6cda0b01a39.uh3m7jq44BFOgwLj4kHoPzzNjRXdtVkHDnNRwQOpwCU
scenes-app-feature-flags--edit-multi-variate-feature-flag--light:
@@ -9420,6 +9432,34 @@ snapshots:
hash: v1.k794b7964.64bc82476828e61d420a9fc2ef3c550d45acf9c24f8d0bec694f803ecd147df7.eqlptg68mBa-l30eKEMGIEqcHeTSh2GAlhd0ybVid-k
scenes-app-people-cohorts--cohort-edit-dynamic--light:
hash: v1.k794b7964.16bae00697363fb140788023823ca272a1f57bf2b9cc4984f62f6b39e098b87a.sga7qTbJWVb7MG-E8DSdsDVlcJm9nBZzZAY6TxrBIUw
+ scenes-app-people-cohorts--cohort-edit-person-properties--dark:
+ hash: v1.k794b7964.c861bd63cb563dc388df44cfacc390a132486e925becb5551d3ac0ae4cffbcf8.IMaQW8Yon_VqNVEE9-tnOtK1lNSyMuwxN9a-4SWgZzU
+ scenes-app-people-cohorts--cohort-edit-person-properties--light:
+ hash: v1.k794b7964.807a4d957649a09c0bf100246a9775fb014f907223253589e37093881012d7ad.Bl-7G3Js_fWVnQosKpAu3X_rHwpzRHzNE1vRW2kT8nk
+ scenes-app-people-cohorts--cohort-edit-realtime-daily--dark:
+ hash: v1.k794b7964.a58ca2763bf4d0ad21bb045e3df40fd66dae0019c4a89b4cb737e65b15fe750e.7RdVV0PgCXVw93t_xhrf1HWZAWgaq3zvBJT4pngMQIk
+ scenes-app-people-cohorts--cohort-edit-realtime-daily--light:
+ hash: v1.k794b7964.4d701ca553c0d342a85d2fdd08ca0bbcb6629649c53f78727d78092398dd1896.o1JWPnOlcTpxJcPTjW9uJn8jqDzGDKS1LQct4B0C9Sw
+ scenes-app-people-cohorts--cohort-edit-realtime-not-available--dark:
+ hash: v1.k794b7964.4847c1eb77cf7e1f6110d265f1bfdb56bc4f0189a70dd2e583b5a5f185d3faae.CsN_IL0uPTuj08TbFDHDm_paheQ8HqyW642RyqgwZdY
+ scenes-app-people-cohorts--cohort-edit-realtime-not-available--light:
+ hash: v1.k794b7964.866758eefcc8d322577356d38b0eae109bc70d4eabf5db82ae3da8cd68789ce4.RXO-YDcFl2jvjmLQqL--j0mzpxS4aP4QYiogAj2W3go
+ scenes-app-people-cohorts--cohort-edit-realtime-preparing--dark:
+ hash: v1.k794b7964.9defa779b81d25f039dbaca787951ff704b9164b8ed30b0a3c22f8fd4971d0bf.zc5GaVgiUk6vXu2IwEypg-IMGY_hMrWaNRLjim6sUco
+ scenes-app-people-cohorts--cohort-edit-realtime-preparing--light:
+ hash: v1.k794b7964.700b9e00f38e5cf186bf66cb69441cd76f4dfd6ffa62685d075cf9549803726f.DLtgnC7-BgsEwtaTe7CfDggyroFSD6npvHisuFQ2Esc
+ scenes-app-people-cohorts--cohort-edit-realtime-ready--dark:
+ hash: v1.k794b7964.ea59791b66afcac2fb6b17109103110cfa6894d73d28feaadd34d043ae996db6.Tfdgur8DZ7q3kmgInIhMJhStne4aR53yux7IErBb_8w
+ scenes-app-people-cohorts--cohort-edit-realtime-ready--light:
+ hash: v1.k794b7964.db7cc98ca551776dad599e2f3eeb42b3f11f7b8f83e895e6911c929d8064f5b2.kh0GmHQxkSVgSu4FH-AW0vDquF3E394dIizr4Catrpc
+ scenes-app-people-cohorts--cohort-edit-realtime-ready-flag-off--dark:
+ hash: v1.k794b7964.37bc61b07982efe2362b9f1b53be9ff92fdef34ee81ea3c27fb85bd06e59c72b.78dmguEbam8nczYdzBuy3sKYNdyuL0EfjchkrGMxwkE
+ scenes-app-people-cohorts--cohort-edit-realtime-ready-flag-off--light:
+ hash: v1.k794b7964.8b9ff865378d2be1c33ea33ba2af40701bd14ed017efb4fe22fc08fdcacabeaf.tQPkU-8mNsMRhArTuUfVseT73s9Jmq5bowgKFwwvOV8
+ scenes-app-people-cohorts--cohort-edit-realtime-rebuilding--dark:
+ hash: v1.k794b7964.a0f634f2653893f153a800999372cfce15cbb4ec8ebd86e942acd28a1462cf3f.BALCFCmvgyITBYveLRY4gx2q2j7TJiZ4ftzPJttYJJY
+ scenes-app-people-cohorts--cohort-edit-realtime-rebuilding--light:
+ hash: v1.k794b7964.9dd0949e76bf5a4adc12e6565a5567e2b0b137713d30a41a624ceb42f29feec8.xxnp0SCxXxc_5AbIHkX6BruWnf3zxtQdSKstzpIY6wI
scenes-app-people-cohorts--cohort-edit-static--dark:
hash: v1.k794b7964.267b40e33b380519b46d4b7b8068b869a6250b5fd446c6335a9e95f683ee2302.jnRu9rG_ZQxTsYzmKQqEbN-aIU3psCpbQN8hV8OsX6Y
scenes-app-people-cohorts--cohort-edit-static--light:
@@ -9444,6 +9484,10 @@ snapshots:
hash: v1.k794b7964.e9b06da7fe302cf5d9f9b89a946bcad3b218de80b09f6d79825dc047e2c47144.XhK5xNwino53Y_bl2MrzUq8l2Z2ecyjSXkuKy4TixjI
scenes-app-people-cohorts--cohorts-with-data--light:
hash: v1.k794b7964.78ccc4aa71cdfa0f7f6992c2f5db9948739489adb7ab3814f097fa6391f66942.5fFxaSpqMWp0-CEO48c4gR5lrxyMVcy6Cp4rgPi3V3Y
+ scenes-app-people-cohorts--cohorts-with-realtime-states--dark:
+ hash: v1.k794b7964.c56a4538831beba5bc0c17b2b12edd782c1e8c56878cc82c2f8518eeb635ef66.UxXvp9_MzDZ7N4n1kuRO9VoUkm2uJ-QJI_jEAAWVWxA
+ scenes-app-people-cohorts--cohorts-with-realtime-states--light:
+ hash: v1.k794b7964.648d83f3b0347ec61c77aae1199aa838b764c7a3ff971d2816d1361ce44fcb11.K1pDUnXN38DpohW1_hz-66qLblcS4ayujL8yaiiZ6bQ
scenes-app-people-cohorts-add-person-to-cohort-modal--modal-empty--dark:
hash: v1.k794b7964.4d6a9ffec03501c8b5d18e07127691b585f229dd60847a3cafb1e7c4d470e5f7.u2PV_7TIzIOqQLmFFxHpFecnxYbFLybvgVHz2ij4jCs
scenes-app-people-cohorts-add-person-to-cohort-modal--modal-empty--light:
diff --git a/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx b/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx
index 6c05b6646d4f..3013c34b527a 100644
--- a/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx
+++ b/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx
@@ -63,6 +63,8 @@ export interface PropertyFiltersProps {
excludedOperators?: ExcludedOperators
selectingKeyOnly?: SelectingKeyOnly
hideBehavioralCohorts?: boolean
+ /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */
+ showCohortFlagTargeting?: boolean
addFilterDocLink?: string
operatorAllowlist?: OperatorValueSelectProps['operatorAllowlist']
hogQLGlobals?: Record<string, any>
@@ -120,6 +122,7 @@ export function PropertyFilters({
excludedOperators,
selectingKeyOnly,
hideBehavioralCohorts,
+ showCohortFlagTargeting,
addFilterDocLink,
operatorAllowlist,
hogQLGlobals,
@@ -232,6 +235,7 @@ export function PropertyFilters({
excludedOperators={excludedOperators}
selectingKeyOnly={selectingKeyOnly}
hideBehavioralCohorts={hideBehavioralCohorts}
+ showCohortFlagTargeting={showCohortFlagTargeting}
size={buttonSize}
addFilterDocLink={addFilterDocLink}
editable={editable}
diff --git a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
index 9407035ddc59..6a4e1fb43b76 100644
--- a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
@@ -37,6 +37,7 @@ import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { AnyPropertyFilter, GroupTypeIndex, PropertyDefinitionType, PropertyFilterType } from '~/types'
+import { CohortRealtimeTag } from 'products/cohorts/frontend/realtime/CohortRealtimeTag'
import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
import { FILTER_ROW_FRAME_CLASSES } from './filterRowFrame'
@@ -79,6 +80,7 @@ export function TaxonomicPropertyFilter({
excludedOperators,
selectingKeyOnly,
hideBehavioralCohorts,
+ showCohortFlagTargeting,
addFilterDocLink,
editable = true,
operatorAllowlist,
@@ -165,13 +167,9 @@ export function TaxonomicPropertyFilter({
// Look up cohort name, if not already provided in filter
const cohortValue =
filter?.type === PropertyFilterType.Cohort && !Array.isArray(filter?.value) ? filter.value : undefined
- const cohortName =
- filter?.type === PropertyFilterType.Cohort
- ? filter.cohort_name ||
- (cohortValue !== undefined
- ? cohortsById[cohortValue]?.name || cohortsById[String(cohortValue)]?.name
- : undefined)
- : undefined
+ const cohort =
+ cohortValue !== undefined ? (cohortsById[cohortValue] ?? cohortsById[String(cohortValue)]) : undefined
+ const cohortName = filter?.type === PropertyFilterType.Cohort ? filter.cohort_name || cohort?.name : undefined
const taxonomicFilter = (
<TaxonomicFilter
@@ -186,6 +184,7 @@ export function TaxonomicPropertyFilter({
excludedProperties={excludedProperties}
optionsFromProp={taxonomicFilterOptionsFromProp}
hideBehavioralCohorts={hideBehavioralCohorts}
+ showCohortFlagTargeting={showCohortFlagTargeting}
selectFirstItem={!cohortOrOtherValue}
endpointFilters={endpointFilters}
hogQLGlobals={hogQLGlobals}
@@ -263,26 +262,36 @@ export function TaxonomicPropertyFilter({
const filterType = filter?.type as PropertyFilterType | undefined
+ // The button truncates its label, so its tooltip is how a long cohort name is read in full. The
+ // wrapper below cannot do that job: it clips rather than wraps, and it would nest the tag's own
+ // tooltip inside the button's. So the tooltip gets the plain string.
+ const cohortLabel = filter?.type === 'cohort' ? cohortName || `Cohort #${filter?.value}` : undefined
+
const filterContent =
- filter?.type === 'cohort'
- ? cohortName || `Cohort #${filter?.value}`
- : filter?.type === PropertyFilterType.EventMetadata && filter?.key?.startsWith('$group_')
- ? filter.label || `Group ${filter?.value}`
- : (filter?.type === PropertyFilterType.Flag ||
- filterType === PropertyFilterType.AccountRelationship ||
- filter?.type === PropertyFilterType.AccountCustomProperty) &&
- filter &&
- 'label' in filter &&
- filter.label
- ? filter.label
- : filter?.key && (
- <PropertyKeyInfo
- value={filter.key}
- disablePopover
- ellipsis
- type={PROPERTY_FILTER_TYPE_TO_TAXONOMIC_FILTER_GROUP_TYPE[filter.type]}
- />
- )
+ filter?.type === 'cohort' ? (
+ <span className="flex items-center gap-2 min-w-0">
+ <span className="truncate">{cohortLabel}</span>
+ {showCohortFlagTargeting && <CohortRealtimeTag realtime={cohort?.realtime} />}
+ </span>
+ ) : filter?.type === PropertyFilterType.EventMetadata && filter?.key?.startsWith('$group_') ? (
+ filter.label || `Group ${filter?.value}`
+ ) : (filter?.type === PropertyFilterType.Flag ||
+ filterType === PropertyFilterType.AccountRelationship ||
+ filter?.type === PropertyFilterType.AccountCustomProperty) &&
+ filter &&
+ 'label' in filter &&
+ filter.label ? (
+ filter.label
+ ) : (
+ filter?.key && (
+ <PropertyKeyInfo
+ value={filter.key}
+ disablePopover
+ ellipsis
+ type={PROPERTY_FILTER_TYPE_TO_TAXONOMIC_FILTER_GROUP_TYPE[filter.type]}
+ />
+ )
+ )
const legacyDropdown = (
<LemonDropdown
@@ -301,7 +310,7 @@ export function TaxonomicPropertyFilter({
truncate={true}
tooltip={
<>
- {filterContent ?? (addText || 'Add filter')}
+ {cohortLabel ?? filterContent ?? (addText || 'Add filter')}
{addFilterDocLink && (
<>
<br />
@@ -347,6 +356,7 @@ export function TaxonomicPropertyFilter({
propertyAllowList={propertyAllowList}
optionsFromProp={taxonomicFilterOptionsFromProp}
hideBehavioralCohorts={hideBehavioralCohorts}
+ showCohortFlagTargeting={showCohortFlagTargeting}
endpointFilters={endpointFilters}
hogQLGlobals={hogQLGlobals}
enableKeywordShortcuts
diff --git a/frontend/src/lib/components/PropertyFilters/types.ts b/frontend/src/lib/components/PropertyFilters/types.ts
index f9c55c110e23..7177340c9aa2 100644
--- a/frontend/src/lib/components/PropertyFilters/types.ts
+++ b/frontend/src/lib/components/PropertyFilters/types.ts
@@ -73,6 +73,8 @@ export interface PropertyFilterInternalProps {
excludedOperators?: ExcludedOperators
selectingKeyOnly?: SelectingKeyOnly
hideBehavioralCohorts?: boolean
+ /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */
+ showCohortFlagTargeting?: boolean
addFilterDocLink?: string
endpointFilters?: Record<string, any>
hogQLGlobals?: Record<string, any>
diff --git a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
index 1ca2074a1e1d..a4d912bd7ecd 100644
--- a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
@@ -607,6 +607,7 @@ export const InfiniteListRow = ({
localListGroup,
fallbackGroup: group ?? itemGroup,
})
+ const itemTag = resolvedItemGroup.getTag?.(item)
return (
<div
@@ -638,6 +639,9 @@ export const InfiniteListRow = ({
isActive,
selectedRenameMeta: isSelected ? getSelectedItemRenameMeta(selectedItemMeta, itemValue) : null,
})}
+ {/* `empty:hidden` because a group's `getTag` returns an element whether or not it renders
+ anything, and an empty `ml-auto` span would shift every row's pin icon. */}
+ {itemTag ? <span className="flex shrink-0 ml-auto pl-2 empty:hidden">{itemTag}</span> : null}
{isCrossGroupItem && (
<LemonTag size="small" type="highlight">
{localListLabel ? `${itemGroup.name} - ${localListLabel}` : itemGroup.name}
diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
index 5f9c698cd7a1..a561419b3134 100644
--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
@@ -7,6 +7,7 @@ import { useEffect } from 'react'
import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__mocks__/taxonomicFilterMocksDecorator'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
@@ -712,6 +713,62 @@ export const FailedFetchOffersRetry: Story = {
},
}
+export const CohortsWithRealtimeStates: Story = {
+ args: {
+ taxonomicFilterLogicKey: 'cohorts-realtime',
+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Cohorts],
+ // The opt-in a feature flag's release conditions set. Without it the rows carry no tag,
+ // which is what every other cohort picker in the app renders.
+ showCohortFlagTargeting: true,
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/cohorts/': [
+ {
+ id: 1,
+ name: 'Viewed pricing this week',
+ count: 4321,
+ is_static: false,
+ realtime: { state: 'ready', ready_at: '2023-07-03T09:40:00Z', build: null },
+ },
+ {
+ id: 2,
+ name: 'Completed onboarding',
+ count: 210,
+ is_static: false,
+ realtime: {
+ state: 'building',
+ ready_at: null,
+ build: { phase: 'scanning', percent_complete: 45, updated_at: '2023-07-03T23:58:00Z' },
+ },
+ },
+ {
+ id: 3,
+ name: 'Churn risk',
+ count: 76,
+ is_static: false,
+ realtime: { state: 'needs_attention', ready_at: null, build: null },
+ },
+ { id: 4, name: 'Beta testers', count: 89, is_static: true, realtime: null },
+ { id: 5, name: 'Signed up last month', count: 1200, is_static: false, realtime: null },
+ ],
+ },
+ }),
+ ],
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING],
+ // The preparing cohort's tag holds a spinner while its build runs, so the runner cannot
+ // wait for every loader to disappear here.
+ testOptions: { waitForLoadersToDisappear: false, waitForSelector: '[data-attr="cohort-realtime-tag"]' },
+ docs: {
+ description: {
+ story: 'Cohort rows carry their realtime state, so someone picking one for a feature flag sees which cohorts flags can already target and which are still being prepared.',
+ },
+ },
+ },
+}
+
export const EmptyEventsWithStaleToggle: Story = {
render: (args) => {
useMountedLogic(actionsModel)
diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx
index d7fb26fe6b91..d2473697185c 100644
--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx
@@ -42,6 +42,7 @@ export function TaxonomicFilter({
selectFirstItem = true,
propertyAllowList,
hideBehavioralCohorts,
+ showCohortFlagTargeting,
showNumericalPropsOnly,
dataWarehousePopoverFields = defaultDataWarehousePopoverFields,
maxContextOptions,
@@ -85,6 +86,7 @@ export function TaxonomicFilter({
metadataSource,
propertyAllowList,
hideBehavioralCohorts,
+ showCohortFlagTargeting,
showNumericalPropsOnly,
dataWarehousePopoverFields,
autoSelectItem: true,
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
index 1aa2d18a34da..39e3fc0006ab 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
@@ -85,6 +85,8 @@ export interface UseTaxonomicFilterOptions {
propertyAllowList?: AllowedProperties
maxContextOptions?: MaxContextTaxonomicFilterOption[]
hideBehavioralCohorts?: boolean
+ /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */
+ showCohortFlagTargeting?: boolean
endpointFilters?: Record<string, any>
hogQLGlobals?: Record<string, any>
hogQLExpressionShowBreakdownLabelHint?: boolean
@@ -289,6 +291,7 @@ export function useTaxonomicFilter(opts: UseTaxonomicFilterOptions): TaxonomicFi
propertyAllowList,
maxContextOptions,
hideBehavioralCohorts,
+ showCohortFlagTargeting,
endpointFilters,
hogQLGlobals,
hogQLExpressionShowBreakdownLabelHint,
@@ -324,6 +327,7 @@ export function useTaxonomicFilter(opts: UseTaxonomicFilterOptions): TaxonomicFi
selectedProperties,
maxContextOptions,
hideBehavioralCohorts,
+ showCohortFlagTargeting,
endpointFilters,
hogQLGlobals,
hogQLExpressionShowBreakdownLabelHint,
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts
index feb877e0156e..f856e31adb39 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts
@@ -55,6 +55,8 @@ export interface UseTaxonomicGroupsContextInput {
selectedProperties?: SelectedProperties
maxContextOptions?: MaxContextTaxonomicFilterOption[]
hideBehavioralCohorts?: boolean
+ /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */
+ showCohortFlagTargeting?: boolean
endpointFilters?: Record<string, any>
hogQLGlobals?: Record<string, any>
hogQLExpressionShowBreakdownLabelHint?: boolean
@@ -148,6 +150,7 @@ export function useTaxonomicGroupsContext(input: UseTaxonomicGroupsContextInput)
personMetadataPropertyDefinitions,
maxContextOptions: input.maxContextOptions ?? (EMPTY_ARRAY as unknown as MaxContextTaxonomicFilterOption[]),
hideBehavioralCohorts: input.hideBehavioralCohorts ?? false,
+ showCohortFlagTargeting: input.showCohortFlagTargeting ?? false,
endpointFilters: input.endpointFilters,
hogQLExpressionComponentProps,
// `featureFlags` from featureFlagLogic returns the project's
@@ -182,6 +185,7 @@ export function useTaxonomicGroupsContext(input: UseTaxonomicGroupsContextInput)
input.propertyAllowList,
input.maxContextOptions,
input.hideBehavioralCohorts,
+ input.showCohortFlagTargeting,
input.endpointFilters,
input.hogQLGlobals,
input.hogQLExpressionShowBreakdownLabelHint,
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
index e411acffbbf3..a8a5605154ae 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
@@ -852,6 +852,25 @@ describe('MenuFilterCombobox', () => {
expect(pinnedRow).toContain('Event properties')
})
+ it('renders the tag a group supplies, from the row it is handed', async () => {
+ // The classic list renders `getTag`, so a group relying on it to mark a row (a cohort that
+ // feature flags cannot target yet) would silently lose that mark in this menu. The tag has
+ // to come off the item, not the group: a recent is stored stripped to its name and id, so
+ // the cohort group's `getTag` gets a record with no readiness on it and renders nothing.
+ const tagged = makeEntry(TaxonomicFilterGroupType.Events, 'my_tagged_event', 'Events')
+ tagged.item.tagLabel = 'Preparing'
+ const stripped = makeEntry(TaxonomicFilterGroupType.Events, 'my_stripped_event', 'Events')
+ const getTag = (item: any): JSX.Element | null => (item?.tagLabel ? <span>{item.tagLabel}</span> : null)
+ tagged.group.getTag = getTag
+ stripped.group.getTag = getTag
+
+ renderAll({ groupTypes: [TaxonomicFilterGroupType.Events], recentEntries: [tagged, stripped] })
+
+ await waitFor(() => expect(rowTexts().some((t) => t.includes('my_tagged_event'))).toBe(true))
+ expect(rowTexts().find((t) => t.includes('my_tagged_event'))).toContain('Preparing')
+ expect(rowTexts().find((t) => t.includes('my_stripped_event'))).not.toContain('Preparing')
+ })
+
it('recent leads the list at row 0 even when content also matches the search query', async () => {
// Endpoint returns a row that matches the same query as the recent.
apiGet.mockImplementation((url: string) => {
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
index a96c3560c0c6..0633d9c29842 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
@@ -1327,6 +1327,7 @@ function Row({
// The committed selection of a renamed series shows the series' name; the raw key
// it queries moves to the value cell, like any other friendly-labelled row.
const isRenamedSelection = isSelected && !!selectedRename && selectedRename.label !== cells.name
+ const itemTag = entry.group.getTag?.(entry.item)
const name = isRenamedSelection ? selectedRename.label : cells.name
const value = isRenamedSelection && selectedRename.raw !== selectedRename.label ? selectedRename.raw : cells.value
const category = cells.category
@@ -1378,6 +1379,9 @@ function Row({
{showCategory && <MenuLabel className="text-tertiary/50 text-xxs p-0 mt-1">{category}</MenuLabel>}
</div>
<MatchedValueBadge entry={entry} />
+ {/* Whatever the group supplies for this item, the same node the classic list renders,
+ so a picker row carries its per-item state in either menu. */}
+ {itemTag && <span className="shrink-0 empty:hidden">{itemTag}</span>}
{recency && (
<Badge variant="default" className="gap-1 shrink-0">
{recency === 'recent' ? <IconClock className="size-3" /> : <IconPinFilled className="size-3" />}
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx
index 72fbd01647af..89e1e22088c0 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx
@@ -6,6 +6,8 @@ import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'
import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__mocks__/taxonomicFilterMocksDecorator'
import { FEATURE_FLAGS } from 'lib/constants'
+import { mswDecorator } from '~/mocks/browser'
+import { toPaginatedResponse } from '~/mocks/handlers'
import { actionsModel } from '~/models/actionsModel'
import { getCoreFilterDefinition } from '~/taxonomy/helpers'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
@@ -483,3 +485,66 @@ export const RecentsBareKeyExpansion: Story = {
},
},
}
+
+function CohortRowsContainer(): JSX.Element {
+ useMountedLogic(actionsModel)
+ return (
+ <TaxonomicFilterHeadless.Root
+ bindRootProps={false}
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]}
+ // The opt-in a feature flag's release conditions set; no other picker tags cohorts.
+ showCohortFlagTargeting
+ >
+ <div className="border rounded overflow-hidden flex flex-col w-[720px] h-[420px] bg-surface-primary">
+ <MenuFilterCombobox
+ drillTo={TaxonomicFilterGroupType.Cohorts}
+ title="Cohorts"
+ onCommit={() => {}}
+ onBack={() => {}}
+ />
+ </div>
+ </TaxonomicFilterHeadless.Root>
+ )
+}
+
+export const CohortsWithRealtimeStates: Story = {
+ render: () => <CohortRowsContainer />,
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/cohorts/': toPaginatedResponse([
+ {
+ id: 1,
+ name: 'Viewed pricing this week',
+ count: 4321,
+ is_static: false,
+ realtime: { state: 'ready', ready_at: '2023-07-03T09:40:00Z', build: null },
+ },
+ {
+ id: 2,
+ name: 'Completed onboarding',
+ count: 210,
+ is_static: false,
+ realtime: {
+ state: 'building',
+ ready_at: null,
+ build: { phase: 'scanning', percent_complete: 45, updated_at: '2023-07-03T23:58:00Z' },
+ },
+ },
+ { id: 3, name: 'Signed up last month', count: 1200, is_static: false, realtime: null },
+ ]),
+ },
+ }),
+ ],
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING],
+ // The preparing cohort's tag holds a spinner while its build runs, so the runner cannot
+ // wait for every loader to disappear here.
+ testOptions: { waitForLoadersToDisappear: false, waitForSelector: '[data-attr="cohort-realtime-tag"]' },
+ docs: {
+ description: {
+ story: 'Cohort rows carry the same realtime tag the classic list shows, so someone picking a cohort for a feature flag sees which ones flags can already target.',
+ },
+ },
+ },
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
index aceae5c76fb5..e0943e4b942a 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx
@@ -118,6 +118,7 @@ import {
TeamType,
} from '~/types'
+import { CohortRealtimeTag } from 'products/cohorts/frontend/realtime/CohortRealtimeTag'
import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
import { experimentsLogic } from 'products/experiments/frontend/scenes/experimentsLogic'
import { groupDisplayId } from 'products/persons/frontend/components/GroupActorDisplay'
@@ -515,6 +516,10 @@ export interface taxonomicFilterLogicValues {
allowNonCapturedEvents: boolean
anyGroupLoading: boolean
anyGroupStale: boolean
+ cohortGroupOptions: {
+ hideBehavioralCohorts: boolean
+ showCohortFlagTargeting: boolean
+ }
currentTabIndex: number
dataWarehousePopoverFields: any
endpointFilters: Record<string, any>
@@ -565,6 +570,7 @@ export interface taxonomicFilterLogicValues {
searchQuery: string
selectedItemMeta: any
selectedProperties: TaxonomicFilterGroupValueMap
+ showCohortFlagTargeting: boolean
showNumericalPropsOnly: any
suggestedFilterGroupOrder: TaxonomicFilterGroupType[]
suggestedFiltersLabel: any
@@ -684,6 +690,14 @@ export interface taxonomicFilterLogicMeta {
}
allowNonCapturedEvents: (arg: any) => boolean
hideBehavioralCohorts: (arg: any) => boolean
+ showCohortFlagTargeting: (arg: any) => boolean
+ cohortGroupOptions: (
+ hideBehavioralCohorts: boolean,
+ showCohortFlagTargeting: boolean
+ ) => {
+ hideBehavioralCohorts: boolean
+ showCohortFlagTargeting: boolean
+ }
hogQLExpressionComponentProps: (
arg: any,
arg2: any
@@ -723,7 +737,10 @@ export interface taxonomicFilterLogicMeta {
person: PropertyDefinition[]
},
maxContextOptions: any,
- hideBehavioralCohorts: boolean,
+ cohortGroupOptions: {
+ hideBehavioralCohorts: boolean
+ showCohortFlagTargeting: boolean
+ },
endpointFilters: Record<string, any>,
hogQLExpressionComponentProps: {
globals?: Record<string, any>
@@ -1065,6 +1082,19 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
() => [(_, props) => props.hideBehavioralCohorts],
(hideBehavioralCohorts: boolean | undefined) => hideBehavioralCohorts ?? false,
],
+ showCohortFlagTargeting: [
+ () => [(_, props) => props.showCohortFlagTargeting],
+ (showCohortFlagTargeting: boolean | undefined) => showCohortFlagTargeting ?? false,
+ ],
+ // The two cohort-group props travel as one input because `taxonomicGroups` already sits at
+ // kea's ceiling of 16 selector inputs.
+ cohortGroupOptions: [
+ (s) => [s.hideBehavioralCohorts, s.showCohortFlagTargeting],
+ (hideBehavioralCohorts: boolean, showCohortFlagTargeting: boolean) => ({
+ hideBehavioralCohorts,
+ showCohortFlagTargeting,
+ }),
+ ],
hogQLExpressionComponentProps: [
() => [(_, props) => props.hogQLGlobals, (_, props) => props.hogQLExpressionShowBreakdownLabelHint],
(
@@ -1104,7 +1134,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
s.propertyFilters,
s.metadataPropertyDefinitionsByType,
s.maxContextOptions,
- s.hideBehavioralCohorts,
+ s.cohortGroupOptions,
s.endpointFilters,
s.hogQLExpressionComponentProps,
s.featureFlags,
@@ -1138,7 +1168,13 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
person: PropertyDefinition[]
},
maxContextOptions: MaxContextTaxonomicFilterOption[],
- hideBehavioralCohorts: boolean,
+ {
+ hideBehavioralCohorts,
+ showCohortFlagTargeting,
+ }: {
+ hideBehavioralCohorts: boolean
+ showCohortFlagTargeting: boolean
+ },
endpointFilters: Record<string, any> | undefined,
hogQLExpressionComponentProps: {
globals?: Record<string, any>
@@ -1777,6 +1813,9 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
clientFilterFirstPage: true,
getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,
getValue: (cohort: CohortType) => cohort.id,
+ getTag: showCohortFlagTargeting
+ ? (cohort: CohortType) => <CohortRealtimeTag realtime={cohort.realtime} />
+ : undefined,
getPopoverHeader: (cohort: CohortType) => `${cohort.is_static ? 'Static' : 'Dynamic'} Cohort`,
getIcon: function _getIcon(): JSX.Element {
return <IconCohort className="taxonomy-icon taxonomy-icon-muted" />
@@ -1798,6 +1837,9 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([
options: COHORTS_WITH_ALL_USERS_OPTIONS,
getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,
getValue: (cohort: CohortType) => cohort.id,
+ getTag: showCohortFlagTargeting
+ ? (cohort: CohortType) => <CohortRealtimeTag realtime={cohort.realtime} />
+ : undefined,
getPopoverHeader: () => `All Users`,
getIcon: function _getIcon(): JSX.Element {
return <IconCohort className="taxonomy-icon taxonomy-icon-muted" />
diff --git a/frontend/src/lib/components/TaxonomicFilter/types.ts b/frontend/src/lib/components/TaxonomicFilter/types.ts
index aa1263cfb231..1914c15b5b07 100644
--- a/frontend/src/lib/components/TaxonomicFilter/types.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/types.ts
@@ -152,6 +152,13 @@ export interface TaxonomicFilterProps {
propertyAllowList?: AllowedProperties // only return properties in this list, currently only working for EventProperties and PersonProperties
metadataSource?: AnyDataNode
hideBehavioralCohorts?: boolean
+ /**
+ * Mark every cohort row with what feature flags can do with it. Set it only where that is the
+ * question the picker is asking, which today is a feature flag's release conditions. The same
+ * cohort groups back every other picker in the app, and a row reading "No flag targeting" in an
+ * insight breakdown describes nothing the reader is choosing.
+ */
+ showCohortFlagTargeting?: boolean
showNumericalPropsOnly?: boolean
dataWarehousePopoverFields?: DataWarehousePopoverField[]
maxContextOptions?: MaxContextTaxonomicFilterOption[]
@@ -265,6 +272,8 @@ export interface TaxonomicFilterGroup {
getValue?: (instance: any) => TaxonomicFilterValue
getPopoverHeader: (instance: any) => string
getIcon?: (instance: any) => JSX.Element
+ /** A small tag after the item's name, for a per-item state a reader should see before selecting it. */
+ getTag?: (instance: any) => ReactNode
/** Determines if an item should be disabled (unselectable) */
getIsDisabled?: (instance: any) => boolean
groupTypeIndex?: number
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
index 5170d97e38a6..d01ce919fe64 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
@@ -73,6 +73,7 @@ import {
TeamType,
} from '~/types'
+import { CohortRealtimeTag } from 'products/cohorts/frontend/realtime/CohortRealtimeTag'
import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
import { experimentsLogic } from 'products/experiments/frontend/scenes/experimentsLogic'
import { HogFlowTaxonomicFilters } from 'products/workflows/frontend/Workflows/hogflows/filters/HogFlowTaxonomicFilters'
@@ -168,6 +169,8 @@ export interface BuildTaxonomicGroupsContext {
personMetadataPropertyDefinitions: PropertyDefinition[]
maxContextOptions: MaxContextTaxonomicFilterOption[]
hideBehavioralCohorts: boolean
+ /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */
+ showCohortFlagTargeting: boolean
endpointFilters: Record<string, any> | undefined
hogQLExpressionComponentProps: {
globals?: Record<string, any>
@@ -195,6 +198,7 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomi
personMetadataPropertyDefinitions,
maxContextOptions,
hideBehavioralCohorts,
+ showCohortFlagTargeting,
endpointFilters,
hogQLExpressionComponentProps,
featureFlags,
@@ -784,6 +788,9 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomi
clientFilterFirstPage: true,
getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,
getValue: (cohort: CohortType) => cohort.id,
+ getTag: showCohortFlagTargeting
+ ? (cohort: CohortType) => <CohortRealtimeTag realtime={cohort.realtime} />
+ : undefined,
getPopoverHeader: (cohort: CohortType) => `${cohort.is_static ? 'Static' : 'Dynamic'} Cohort`,
getIcon: function _getIcon(): JSX.Element {
return <IconCohort className="taxonomy-icon taxonomy-icon-muted" />
@@ -805,6 +812,9 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomi
options: COHORTS_WITH_ALL_USERS_OPTIONS,
getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,
getValue: (cohort: CohortType) => cohort.id,
+ getTag: showCohortFlagTargeting
+ ? (cohort: CohortType) => <CohortRealtimeTag realtime={cohort.realtime} />
+ : undefined,
getPopoverHeader: () => `All Users`,
getIcon: function _getIcon(): JSX.Element {
return <IconCohort className="taxonomy-icon taxonomy-icon-muted" />
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts b/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts
index 36ded9a9c5d8..fb481faf1baa 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts
@@ -66,6 +66,7 @@ describe('mcpProperties', () => {
personMetadataPropertyDefinitions: [],
maxContextOptions: [],
hideBehavioralCohorts: false,
+ showCohortFlagTargeting: false,
endpointFilters: undefined,
hogQLExpressionComponentProps: { showBreakdownLabelHint: false },
featureFlags: {},
diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx
index b5c746d504e1..ba9991d59cec 100644
--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx
+++ b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx
@@ -87,6 +87,8 @@ export interface TaxonomicPopoverMenuProps<ValueType extends TaxonomicFilterValu
propertyAllowList?: AllowedProperties
optionsFromProp?: Partial<Record<TaxonomicFilterGroupType, SimpleOption[]>>
hideBehavioralCohorts?: boolean
+ /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */
+ showCohortFlagTargeting?: boolean
endpointFilters?: Record<string, any>
hogQLGlobals?: Record<string, any>
showNumericalPropsOnly?: boolean
@@ -226,6 +228,7 @@ function ArmedTaxonomicPopoverMenu<ValueType extends TaxonomicFilterValue = Taxo
propertyAllowList,
optionsFromProp,
hideBehavioralCohorts,
+ showCohortFlagTargeting,
endpointFilters,
hogQLGlobals,
showNumericalPropsOnly,
@@ -310,6 +313,7 @@ function ArmedTaxonomicPopoverMenu<ValueType extends TaxonomicFilterValue = Taxo
propertyAllowList={propertyAllowList}
optionsFromProp={optionsFromProp}
hideBehavioralCohorts={hideBehavioralCohorts}
+ showCohortFlagTargeting={showCohortFlagTargeting}
endpointFilters={endpointFilters}
hogQLGlobals={hogQLGlobals}
showNumericalPropsOnly={showNumericalPropsOnly}
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index 4fdbe775045b..9a719191269e 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -54,6 +54,7 @@ import { Query } from '~/queries/Query/Query'
import { ActivityScope, CohortType, InsightShortId, SidePanelTab } from '~/types'
import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'
+import { CohortRealtimeStatus } from 'products/cohorts/frontend/realtime/CohortRealtimeStatus'
import { AddPersonToCohortModal } from './AddPersonToCohortModal'
import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'
@@ -544,6 +545,11 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
{!cohort.is_static && (
<div className="flex items-center gap-x-2 my-0">
<strong>Last calculated:</strong>
+ {featureFlags[FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING] && (
+ <Tooltip title="When PostHog last worked out who belongs to this cohort. That count is what insights, breakdowns and the people list below use, and it is recalculated once a day and whenever you edit the cohort.">
+ <IconInfo className="text-secondary text-base" />
+ </Tooltip>
+ )}
{isCalculatingOrPending ? (
<div className="flex items-center gap-x-2">
<Spinner size="small" />
@@ -603,6 +609,10 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
</div>
)}
+ {!isNewCohort && !cohort.is_static && (
+ <CohortRealtimeStatus realtime={cohort.realtime} />
+ )}
+
{!isNewCohort && usedIn && (
<UsedInSummary
usedIn={usedIn}
diff --git a/frontend/src/scenes/cohorts/Cohorts.stories.tsx b/frontend/src/scenes/cohorts/Cohorts.stories.tsx
index 5e315003504f..b52eea7adfbb 100644
--- a/frontend/src/scenes/cohorts/Cohorts.stories.tsx
+++ b/frontend/src/scenes/cohorts/Cohorts.stories.tsx
@@ -1,5 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
+import { FEATURE_FLAGS } from 'lib/constants'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
@@ -15,6 +16,7 @@ const meta: Meta = {
viewMode: 'story',
mockDate: '2023-07-04',
testOptions: { viewport: { width: 1300, height: 2000 } },
+ featureFlags: [FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING],
},
}
export default meta
@@ -42,6 +44,45 @@ const mockCohorts: CohortType[] = [
createCohort(3, 'Beta testers', 89, true),
]
+const withRealtime = (cohort: CohortType, realtime: CohortType['realtime']): CohortType => ({ ...cohort, realtime })
+
+const realtimeCohorts: CohortType[] = [
+ withRealtime(createCohort(4, 'Viewed pricing this week', 4321, false), {
+ state: 'ready',
+ ready_at: '2023-07-03T09:40:00Z',
+ build: null,
+ }),
+ // Just saved: the daily calculation and the realtime build run at the same time, and the page
+ // has to keep the two apart.
+ withRealtime(createCohort(5, 'Completed onboarding', 210, false, true), {
+ state: 'building',
+ ready_at: null,
+ build: { phase: 'scanning', percent_complete: 45, updated_at: '2023-07-03T23:58:00Z' },
+ }),
+ withRealtime(
+ { ...createCohort(6, 'Churn risk', 76, false), description: 'Logged in less than twice in the last month' },
+ {
+ state: 'needs_attention',
+ ready_at: null,
+ build: null,
+ }
+ ),
+ // Event criteria the realtime path does not support, so flags cannot target it at all. A
+ // cohort demoted past the person-count ceiling lands here too, which is the case worth seeing.
+ withRealtime(createCohort(7, 'Stopped using search', 512, false), {
+ state: 'daily',
+ ready_at: null,
+ build: null,
+ }),
+ // Person properties alone: flags read those as they evaluate, so this row carries no tag and
+ // the page still answers the question. A bare row means one thing, and this is that one thing.
+ withRealtime(createCohort(8, 'Signed up this month', 1200, false), {
+ state: 'person_properties',
+ ready_at: null,
+ build: null,
+ }),
+]
+
const cohortApiMocks = {
'/api/projects/:team_id/actions/': toPaginatedResponse([]),
'/api/projects/:team_id/cohorts/': toPaginatedResponse(mockCohorts),
@@ -63,6 +104,23 @@ export const CohortsEmpty: Story = {
decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/': toPaginatedResponse([]) } })],
}
+// The preparing cohort's tag holds a spinner for as long as its build runs, and the runner waits
+// for every loader to disappear before it snapshots. These stories name the element to wait for
+// instead. The runner freezes animations, so a spinner still snapshots deterministically.
+const progressTestOptions = {
+ waitForLoadersToDisappear: false,
+ waitForSelector: '[data-attr="cohort-realtime-tag"]',
+}
+
+export const CohortsWithRealtimeStates: Story = {
+ parameters: { pageUrl: urls.cohorts(), testOptions: progressTestOptions },
+ decorators: [
+ mswDecorator({
+ get: { '/api/projects/:team_id/cohorts/': toPaginatedResponse([...mockCohorts, ...realtimeCohorts]) },
+ }),
+ ],
+}
+
export const CohortNew: Story = {
parameters: { pageUrl: urls.cohort('new') },
decorators: [mswDecorator({ get: cohortApiMocks })],
@@ -73,6 +131,62 @@ export const CohortEditDynamic: Story = {
decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/1/': mockCohorts[0], ...cohortApiMocks } })],
}
+export const CohortEditRealtimeReady: Story = {
+ parameters: { pageUrl: urls.cohort(4) },
+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/4/': realtimeCohorts[0], ...cohortApiMocks } })],
+}
+
+// Pins the flag-off page: without the rollout flag, a realtime cohort must look like any dynamic cohort.
+export const CohortEditRealtimeReadyFlagOff: Story = {
+ parameters: { pageUrl: urls.cohort(4), featureFlags: [] },
+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/4/': realtimeCohorts[0], ...cohortApiMocks } })],
+}
+
+export const CohortEditRealtimePreparing: Story = {
+ parameters: {
+ pageUrl: urls.cohort(5),
+ testOptions: { waitForLoadersToDisappear: false, waitForSelector: '[data-attr="cohort-realtime-status"]' },
+ },
+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/5/': realtimeCohorts[1], ...cohortApiMocks } })],
+}
+
+export const CohortEditRealtimeRebuilding: Story = {
+ parameters: {
+ pageUrl: urls.cohort(5),
+ testOptions: { waitForLoadersToDisappear: false, waitForSelector: '[data-attr="cohort-realtime-status"]' },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/cohorts/5/': withRealtime(
+ { ...realtimeCohorts[1], is_calculating: false },
+ {
+ state: 'rebuilding',
+ ready_at: null,
+ build: { phase: 'checking', percent_complete: null, updated_at: '2023-07-03T23:58:00Z' },
+ }
+ ),
+ ...cohortApiMocks,
+ },
+ }),
+ ],
+}
+
+export const CohortEditRealtimeNotAvailable: Story = {
+ parameters: { pageUrl: urls.cohort(6) },
+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/6/': realtimeCohorts[2], ...cohortApiMocks } })],
+}
+
+export const CohortEditRealtimeDaily: Story = {
+ parameters: { pageUrl: urls.cohort(7) },
+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/7/': realtimeCohorts[3], ...cohortApiMocks } })],
+}
+
+export const CohortEditPersonProperties: Story = {
+ parameters: { pageUrl: urls.cohort(8) },
+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/8/': realtimeCohorts[4], ...cohortApiMocks } })],
+}
+
export const CohortEditStatic: Story = {
parameters: { pageUrl: urls.cohort(3) },
decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/3/': mockCohorts[2], ...cohortApiMocks } })],
diff --git a/frontend/src/scenes/cohorts/Cohorts.tsx b/frontend/src/scenes/cohorts/Cohorts.tsx
index 6ce7f429e4fd..81f3e9d27d78 100644
--- a/frontend/src/scenes/cohorts/Cohorts.tsx
+++ b/frontend/src/scenes/cohorts/Cohorts.tsx
@@ -10,6 +10,7 @@ import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'
import { dayjs } from 'lib/dayjs'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
@@ -37,6 +38,7 @@ import {
} from '~/types'
import { cohortsEmptyState } from 'products/cohorts/frontend/emptyState/cohortsEmptyState'
+import { CohortRealtimeTag } from 'products/cohorts/frontend/realtime/CohortRealtimeTag'
export const scene: SceneExport = {
component: Cohorts,
@@ -51,6 +53,7 @@ export function Cohorts(): JSX.Element {
const { deleteCohort, exportCohortPersons, setCohortFilters, setCohortSorting, loadCohorts } =
useActions(cohortsSceneLogic)
const { searchParams } = useValues(router)
+ const realtimeTargetingEnabled = useFeatureFlag('REALTIME_COHORT_FLAG_TARGETING')
// Creating an export requires editor access to the export resource.
const exportAccessControlDisabledReason = getAccessControlDisabledReason(
@@ -64,15 +67,20 @@ export function Cohorts(): JSX.Element {
dataIndex: 'name',
width: '30%',
sorter: (a, b) => (a.name || '').localeCompare(b.name || ''),
- render: function Render(name, { id, description }) {
+ render: function Render(name, { id, description, realtime }) {
return (
- <>
- <LemonTableLink
- to={combineUrl(urls.cohort(id), searchParams).url}
- title={name ? <>{name}</> : 'Untitled'}
- description={description}
- />
- </>
+ <LemonTableLink
+ to={combineUrl(urls.cohort(id), searchParams).url}
+ // In the title rather than beside the link, so a row with a description
+ // keeps the state on the name's line instead of wrapping under it.
+ title={
+ <>
+ {name || 'Untitled'}
+ <CohortRealtimeTag realtime={realtime} />
+ </>
+ }
+ description={description}
+ />
)
},
},
@@ -89,8 +97,9 @@ export function Cohorts(): JSX.Element {
createdAtColumn<CohortType>() as LemonTableColumn<CohortType, keyof CohortType | undefined>,
{
title: 'Last calculated',
- tooltip:
- 'PostHog calculates what users belong to each cohort. This is then used when filtering on cohorts in the Trends page etc. Calculating happens every 24 hours, or whenever a cohort is updated',
+ tooltip: realtimeTargetingEnabled
+ ? 'When PostHog last worked out who belongs to this cohort. That count is what insights, breakdowns and the people list use, and it is recalculated once a day and whenever the cohort is edited.'
+ : 'PostHog calculates what users belong to each cohort. This is then used when filtering on cohorts in the Trends page etc. Calculating happens every 24 hours, or whenever a cohort is updated',
render: function RenderCalculation(_: any, cohort: CohortType) {
if (cohort.is_static) {
return <>N/A</>
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
index 6bc84356750f..fec386acbcf8 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
@@ -7,7 +7,8 @@ import { v4 as uuidv4 } from 'uuid'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { scrollToFormError } from 'lib/forms/scrollToFormError'
-import { CohortLogicProps, cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { CohortLogicProps, REALTIME_POLL_INTERVAL_MS, cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'
import { CRITERIA_VALIDATIONS, NEW_CRITERIA, ROWS } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
import { teamLogic } from 'scenes/teamLogic'
@@ -29,7 +30,10 @@ import {
TimeUnitType,
} from '~/types'
-import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'
+import type {
+ CohortRealtimeReadinessApi,
+ CohortUsedInResponseApi,
+} from 'products/cohorts/frontend/generated/api.schemas'
jest.mock('uuid', () => ({
v4: jest.fn().mockReturnValue('mocked-uuid'),
@@ -198,6 +202,186 @@ describe('cohortEditLogic', () => {
})
})
+ describe('realtime history build polling', () => {
+ // No feature flag setup: the API only sends `realtime` inside the rollout, so gating the
+ // poll on the flag as well would strand a build whose flags resolve after the page fetch.
+ afterEach(() => {
+ // One case varies the generated criteria keys; the rest of the file reads the constant.
+ ;(uuidv4 as jest.Mock).mockReturnValue('mocked-uuid')
+ })
+
+ const buildingRealtime: CohortRealtimeReadinessApi = {
+ state: 'building',
+ ready_at: null,
+ build: { phase: 'scanning', percent_complete: 40, updated_at: '2026-09-15T10:00:00Z' },
+ }
+ const readyRealtime: CohortRealtimeReadinessApi = {
+ state: 'ready',
+ ready_at: '2026-09-15T10:20:00Z',
+ build: null,
+ }
+ const criteriaGroupKeys = (): (string | undefined)[] =>
+ logic.values.cohort.filters.properties.values.map((group) => (group as CohortCriteriaGroupFilter).sort_key)
+ const setPageHidden = (hidden: boolean): void => {
+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
+ document.dispatchEvent(new Event('visibilitychange'))
+ }
+
+ it('merges the readiness without discarding unsaved criteria', async () => {
+ // The build runs for tens of minutes, so every poll lands on a form the user may be
+ // part-way through editing. Merging the whole cohort back would throw those edits away,
+ // and re-keying the criteria groups would remount the fields they are typing in.
+ let nextKey = 0
+ ;(uuidv4 as jest.Mock).mockImplementation(() => `criteria-key-${nextKey++}`)
+ useMocks({
+ get: { '/api/projects/:team_id/cohorts/:id/': { ...mockCohort, realtime: readyRealtime } },
+ })
+ await initCohortLogic({ id: 1 })
+ await expectLogic(logic, () => {
+ logic.actions.setCohort({ ...mockCohort, realtime: buildingRealtime })
+ logic.actions.setOuterGroupsType(FilterLogicalOperator.And)
+ }).toMatchValues({ cohort: partial({ realtime: buildingRealtime }) })
+ const keysBeforePoll = criteriaGroupKeys()
+
+ await expectLogic(logic, () => {
+ logic.actions.pollRealtimeReadiness()
+ })
+ .toDispatchActions(['pollRealtimeReadiness', 'armRealtimeReadinessPoll'])
+ .toFinishAllListeners()
+ .toMatchValues({
+ cohort: partial({
+ realtime: readyRealtime,
+ filters: partial({ properties: partial({ type: FilterLogicalOperator.And }) }),
+ }),
+ })
+ expect(criteriaGroupKeys()).toEqual(keysBeforePoll)
+ })
+
+ it('drops a readiness the save it crossed has already replaced', async () => {
+ // A poll in flight answers for the definition before the save, so letting it land would
+ // report the old build as ready and stop watching the one the save just started.
+ useMocks({
+ get: { '/api/projects/:team_id/cohorts/:id/': { ...mockCohort, realtime: readyRealtime } },
+ })
+ await initCohortLogic({ id: 1 })
+ await expectLogic(logic, () => {
+ logic.actions.setCohort({ ...mockCohort, realtime: buildingRealtime })
+ }).toMatchValues({ cohort: partial({ realtime: buildingRealtime }) })
+
+ const rebuildingRealtime: CohortRealtimeReadinessApi = { ...buildingRealtime, state: 'rebuilding' }
+ await expectLogic(logic, () => {
+ logic.actions.pollRealtimeReadiness()
+ logic.actions.saveCohortSuccess({ ...mockCohort, realtime: rebuildingRealtime })
+ }).toFinishAllListeners()
+
+ expect(logic.values.cohort.realtime).toEqual(rebuildingRealtime)
+ expect(lemonToast.success).not.toHaveBeenCalled()
+ })
+
+ it('keeps checking while the build runs, and stops once it is ready', async () => {
+ // Both halves matter. A loop that never stops refetches the cohort every 15 seconds for
+ // as long as the tab is open; one that stops early freezes the progress row until reload.
+ let served: CohortRealtimeReadinessApi = buildingRealtime
+ let detailFetches = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/cohorts/:id/': () => {
+ detailFetches += 1
+ return [200, { ...mockCohort, realtime: served }]
+ },
+ },
+ })
+ await initCohortLogic({ id: 1 })
+ const afterMount = detailFetches
+
+ jest.useFakeTimers()
+ try {
+ // The mount armed the poll on a real timer. Arming again replaces that disposable
+ // with one on the fake clock, which is the same timer the loop re-arms below.
+ logic.actions.armRealtimeReadinessPoll()
+
+ await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
+ expect(detailFetches).toBe(afterMount + 1)
+
+ served = readyRealtime
+ await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
+ expect(detailFetches).toBe(afterMount + 2)
+ // The flag picker rows and the condition link read readiness off the shared model,
+ // so without this push they keep showing the cohort as unprepared all session.
+ expect(cohortsModel.values.cohortsById[mockCohort.id]?.realtime).toEqual(readyRealtime)
+
+ await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS * 4)
+ expect(detailFetches).toBe(afterMount + 2)
+
+ // Stopping means disposing, not just declining to re-arm. The disposables manager
+ // re-runs every registered setup when the tab comes back, so a poll left on it
+ // refetches the cohort 15 seconds after each return to a page that is long done.
+ setPageHidden(true)
+ setPageHidden(false)
+ await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
+ expect(detailFetches).toBe(afterMount + 2)
+ } finally {
+ jest.useRealTimers()
+ delete (document as any).hidden
+ }
+ })
+
+ it('keeps watching across the gap between the queued build and its run row', async () => {
+ // The debounce key expires exactly when the run-creation task fires, and the run row
+ // lands a moment later. A poll in between answers `needs_attention` for a build that is
+ // fine, so stopping there would leave the page on "Unavailable" until a reload.
+ let served: CohortRealtimeReadinessApi = buildingRealtime
+ let detailFetches = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/cohorts/:id/': () => {
+ detailFetches += 1
+ return [200, { ...mockCohort, realtime: served }]
+ },
+ },
+ })
+ await initCohortLogic({ id: 1 })
+ const afterMount = detailFetches
+
+ jest.useFakeTimers()
+ try {
+ logic.actions.armRealtimeReadinessPoll()
+
+ served = { state: 'needs_attention', ready_at: null, build: null }
+ await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
+ expect(detailFetches).toBe(afterMount + 1)
+
+ served = readyRealtime
+ await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
+ expect(detailFetches).toBe(afterMount + 2)
+ expect(logic.values.cohort.realtime).toEqual(readyRealtime)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('announces the ready moment once, not on every check after it', async () => {
+ useMocks({
+ get: { '/api/projects/:team_id/cohorts/:id/': { ...mockCohort, realtime: readyRealtime } },
+ })
+ await initCohortLogic({ id: 1 })
+ await expectLogic(logic, () => {
+ logic.actions.setCohort({ ...mockCohort, realtime: buildingRealtime })
+ }).toMatchValues({ cohort: partial({ realtime: buildingRealtime }) })
+
+ await expectLogic(logic, () => {
+ logic.actions.pollRealtimeReadiness()
+ }).toFinishAllListeners()
+ expect(lemonToast.success).toHaveBeenCalledWith('This cohort is ready. Feature flags can target it now.')
+
+ ;(lemonToast.success as jest.Mock).mockClear()
+ await expectLogic(logic, () => {
+ logic.actions.pollRealtimeReadiness()
+ }).toFinishAllListeners()
+ expect(lemonToast.success).not.toHaveBeenCalled()
+ })
+ })
+
it('delete cohort', async () => {
await initCohortLogic({ id: 1 })
await expectLogic(logic, async () => {
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index 5e2350ae37e6..9df7702df5d4 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -65,7 +65,11 @@ import {
} from '~/types'
import { cohortsUsedInRetrieve } from 'products/cohorts/frontend/generated/api'
-import type { CohortUsedInResponseApi } from 'products/cohorts/frontend/generated/api.schemas'
+import type {
+ CohortRealtimeReadinessApi,
+ CohortRealtimeStateEnumApi,
+ CohortUsedInResponseApi,
+} from 'products/cohorts/frontend/generated/api.schemas'
import { personsLogic } from 'products/persons/frontend/logics/personsLogic'
import type { UserBasicType } from '../../types'
@@ -80,6 +84,21 @@ export type CohortEditTab = 'overview' | 'history'
const isCohortEditTab = (value: unknown): value is CohortEditTab => value === 'overview' || value === 'history'
+// While history is being built, flags can't target the cohort yet, so the scene keeps asking. The
+// build takes tens of minutes, so this is slow polling, unlike the 1s loop the daily calculation uses.
+export const REALTIME_POLL_INTERVAL_MS = 15_000
+const BUILDING_STATES: CohortRealtimeStateEnumApi[] = ['building', 'rebuilding']
+
+const isBuildingHistory = (cohort: CohortType): boolean =>
+ !!cohort.realtime && BUILDING_STATES.includes(cohort.realtime.state)
+
+// A queued build and a running one are recorded in two places that do not overlap: a Redis key
+// that expires exactly when the run-creation task fires, and the run row that task then writes. A
+// poll landing between the two reads `needs_attention` for a build that is fine, so a cohort seen
+// building keeps being checked for about a minute. Long enough to cross that gap, and bounded, so
+// a cohort nothing is preparing is not polled for as long as its page stays open.
+const READINESS_GRACE_POLLS = 4
+
const checkIsPendingCalculation = (cohort: CohortType): boolean =>
cohort.pending_version != null &&
(cohort.version == null || cohort.pending_version !== cohort.version) &&
@@ -149,6 +168,9 @@ export interface cohortEditLogicActions {
addPersonToCreateStaticCohort: (personId: string) => {
personId: string
}
+ armRealtimeReadinessPoll: () => {
+ value: true
+ }
checkIfFinishedCalculating: (cohort: CohortType) => {
cohort: CohortType
}
@@ -246,6 +268,9 @@ export interface cohortEditLogicActions {
newGroup: Partial<CohortGroupType>
}
}
+ pollRealtimeReadiness: () => {
+ value: true
+ }
refreshPersonsData: () => {
value: true
}
@@ -381,6 +406,9 @@ export interface cohortEditLogicActions {
setQuery: (query: Node) => {
query: Node<Record<string, any>>
}
+ setRealtimeReadiness: (realtime: CohortType['realtime']) => {
+ realtime: CohortRealtimeReadinessApi | null | undefined
+ }
setStaticCohortMode: (mode: StaticCohortMode) => {
mode: StaticCohortMode
}
@@ -442,6 +470,7 @@ export interface cohortEditLogicActions {
last_import_unmatched_count?: number | null | undefined
name?: string | undefined
pending_version?: number | null | undefined
+ realtime?: CohortRealtimeReadinessApi | null | undefined
version?: number | null | undefined
},
payload?: {
@@ -473,6 +502,7 @@ export interface cohortEditLogicActions {
last_import_unmatched_count?: number | null | undefined
name?: string | undefined
pending_version?: number | null | undefined
+ realtime?: CohortRealtimeReadinessApi | null | undefined
version?: number | null | undefined
}
payload?: {
@@ -519,6 +549,9 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
onCriteriaChange: (newGroup: Partial<CohortGroupType>, id: string) => ({ newGroup, id }),
setPollTimeout: (pollTimeout: number | null) => ({ pollTimeout }),
checkIfFinishedCalculating: (cohort: CohortType) => ({ cohort }),
+ armRealtimeReadinessPoll: true,
+ pollRealtimeReadiness: true,
+ setRealtimeReadiness: (realtime: CohortType['realtime']) => ({ realtime }),
setOuterGroupsType: (type: FilterLogicalOperator) => ({ type }),
setFilterTestAccounts: (filterTestAccounts: boolean) => ({ filterTestAccounts }),
@@ -549,6 +582,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
cohort: [
NEW_COHORT,
{
+ setRealtimeReadiness: (state, { realtime }) => ({ ...state, realtime }),
setOuterGroupsType: (state, { type }) => ({
...state,
filters: {
@@ -1066,7 +1100,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
},
],
})),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
setCriteria: ({ newCriteria, groupIndex, criteriaIndex }) => {
// When the person property key changes, auto-reset the operator to match the
// property type (DateTime → "on the date", non-DateTime → "equals").
@@ -1133,6 +1167,73 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
'There was an error submitting this cohort. Make sure the cohort filters are correct.',
})
},
+ armRealtimeReadinessPoll: () => {
+ // No feature flag check here. The API sends `realtime` only inside the rollout, so a
+ // build state on the cohort is itself the answer, and flags that arrive after the
+ // fetch cannot leave a running build unwatched.
+ if (isBuildingHistory(values.cohort)) {
+ cache.readinessGracePolls = READINESS_GRACE_POLLS
+ } else if (values.cohort.realtime?.state === 'needs_attention' && cache.readinessGracePolls > 0) {
+ cache.readinessGracePolls -= 1
+ } else {
+ // Disposing rather than just returning. The manager re-runs a registered setup
+ // every time the tab comes back, so a poll left on it would refetch the cohort
+ // 15 seconds after each return to a page whose build finished long ago.
+ cache.disposables.dispose('realtimeReadinessPoll')
+ return
+ }
+ cache.disposables.add(() => {
+ const timeoutId = window.setTimeout(() => actions.pollRealtimeReadiness(), REALTIME_POLL_INTERVAL_MS)
+ return () => window.clearTimeout(timeoutId)
+ }, 'realtimeReadinessPoll')
+ },
+ pollRealtimeReadiness: async (_, breakpoint) => {
+ const id = values.cohort.id
+ if (typeof id !== 'number') {
+ return
+ }
+
+ const wasBuilding = isBuildingHistory(values.cohort)
+ // A save lands a fresher readiness than a request already in flight, so a response
+ // that crosses one is dropped. `breakpoint()` cannot catch that: a save dispatches
+ // its own actions, never this one.
+ const generation = cache.realtimeReadinessGeneration ?? 0
+ try {
+ const fetched = await api.cohorts.get(id)
+ breakpoint()
+ if (generation !== (cache.realtimeReadinessGeneration ?? 0)) {
+ return
+ }
+ // Only the readiness merges back, and not through the cohort loader: the user may
+ // be part-way through editing the criteria, and the loader's normalization mints a
+ // new React key for every criteria group, remounting the fields they are typing in.
+ actions.setRealtimeReadiness(fetched.realtime ?? null)
+ // The flag condition chip reads readiness off the shared model, so it would keep
+ // showing this cohort as unprepared for the rest of the session otherwise.
+ cohortsModel.actions.updateCohort(fetched)
+ if (wasBuilding && fetched.realtime?.state === 'ready') {
+ lemonToast.success('This cohort is ready. Feature flags can target it now.')
+ }
+ } catch (error: any) {
+ if (isBreakpoint(error)) {
+ return
+ }
+ // Keep watching: a failed request says nothing about the build, and dropping the
+ // banner would read as the build having finished.
+ }
+ actions.armRealtimeReadinessPoll()
+ },
+ // Both entry points already carry a fresh readiness, the fetch from the page load and the
+ // save from its own response, so they only have to start the clock. Bumping the generation
+ // retires whatever poll was in flight, whose answer describes the definition before this one.
+ fetchCohortSuccess: () => {
+ cache.realtimeReadinessGeneration = (cache.realtimeReadinessGeneration ?? 0) + 1
+ actions.armRealtimeReadinessPoll()
+ },
+ saveCohortSuccess: () => {
+ cache.realtimeReadinessGeneration = (cache.realtimeReadinessGeneration ?? 0) + 1
+ actions.armRealtimeReadinessPoll()
+ },
checkIfFinishedCalculating: async ({ cohort }, breakpoint) => {
const isPendingCalculation = checkIsPendingCalculation(cohort)
const isCalculatingOrPending = cohort.is_calculating || isPendingCalculation
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
index 5d80c82471de..e2345c5e7043 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx
@@ -15,7 +15,7 @@ import { INSTANTLY_AVAILABLE_PROPERTIES } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { GroupsAccessStatus, groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
import { GroupsIntroductionOption } from 'lib/introductions/GroupsIntroductionOption'
-import { IconArrowDown, IconArrowUp, IconErrorOutline, IconOpenInNew, IconSubArrowRight } from 'lib/lemon-ui/icons'
+import { IconArrowDown, IconArrowUp, IconErrorOutline, IconSubArrowRight } from 'lib/lemon-ui/icons'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
@@ -44,6 +44,7 @@ import {
PropertyOperator,
} from '~/types'
+import { CohortConditionLink } from 'products/feature_flags/frontend/CohortConditionLink'
import { FractionalRolloutWarning } from 'products/feature_flags/frontend/FractionalRolloutWarning'
import { resolveAggregationGroupTypeIndex } from './aggregation'
@@ -68,11 +69,7 @@ function PropertyValueComponent({
getDistinctIdName: (distinctId: string) => string
}): JSX.Element {
if (property.type === PropertyFilterType.Cohort) {
- return (
- <LemonButton type="secondary" size="xsmall" to={urls.cohort(property.value)} sideIcon={<IconOpenInNew />}>
- {property.cohort_name || `ID ${property.value}`}
- </LemonButton>
- )
+ return <CohortConditionLink property={property} />
}
if (property.value === PropertyOperator.IsNotSet || property.value === PropertyOperator.IsSet) {
@@ -392,6 +389,7 @@ export function FeatureFlagReleaseConditions({
}
errorMessages={getPropertySelectErrorMessages(propertySelectErrors, index)}
hideBehavioralCohorts={!realtimeCohortFlagTargeting}
+ showCohortFlagTargeting
/>
</div>
)}
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
index b431bfb02653..80a38ddf6409 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx
@@ -652,6 +652,7 @@ const ConditionContent = ({
hasRowOperator={false}
errorMessages={getPropertySelectErrorMessages(propertySelectErrors, index)}
hideBehavioralCohorts={!realtimeCohortFlagTargeting}
+ showCohortFlagTargeting
/>
</div>
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
index 53e26f5e6703..bc91ce6bc7d6 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
@@ -1,10 +1,12 @@
import { Meta, StoryObj } from '@storybook/react'
import { waitFor } from '@testing-library/dom'
+import { FEATURE_FLAGS } from 'lib/constants'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
+import { toPaginatedResponse } from '~/mocks/handlers'
import featureFlags from './__mocks__/feature_flags.json'
import { featureFlagLogic } from './featureFlagLogic'
@@ -21,11 +23,22 @@ const meta: Meta = {
mockDate: '2023-01-28', // To stabilize relative dates
pageUrl: urls.featureFlags(),
testOptions: { viewport: { width: 1300, height: 2000 } },
+ featureFlags: [FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING],
},
decorators: [
mswDecorator({
get: {
'/api/projects/:team_id/integrations': {},
+ '/api/projects/:team_id/cohorts/': toPaginatedResponse([
+ {
+ id: 1,
+ name: 'Viewed pricing this week',
+ count: 4321,
+ is_static: false,
+ filters: { properties: { type: 'AND', values: [] } },
+ realtime: { state: 'ready', ready_at: '2023-01-27T09:40:00Z', build: null },
+ },
+ ]),
'/api/projects/:team_id/feature_flags': featureFlags,
'/api/projects/:team_id/feature_flags/1111111111111/': [
@@ -113,6 +126,36 @@ export const EditFeatureFlag: Story = {
},
}
+export const EditFeatureFlagConditionsWithRealtimeCohort: Story = {
+ parameters: {
+ pageUrl: `${urls.featureFlag(1779)}?edit=true`,
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+ play: async ({ canvasElement }) => {
+ // Condition sets start collapsed, and the realtime tag sits on the expanded cohort row.
+ const expandAll = await waitFor(
+ () => {
+ const button = canvasElement.querySelector<HTMLButtonElement>('[data-attr="expand-all-conditions"]')
+ if (!button) {
+ throw new Error('release conditions for flag 1779 not yet rendered')
+ }
+ return button
+ },
+ // The flag scene is a lazy chunk, so give a cold bundle time to arrive.
+ { timeout: 30000 }
+ )
+ expandAll.click()
+ await waitFor(
+ () => {
+ if (!canvasElement.querySelector('[data-attr="collapse-all-conditions"]')) {
+ throw new Error('condition sets not expanded yet')
+ }
+ },
+ { timeout: 5000 }
+ )
+ },
+}
+
export const EditMultiVariateFeatureFlag: Story = {
parameters: {
pageUrl: urls.featureFlag(1502),
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index d11e11c87d16..07746e5490ea 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -82,6 +82,7 @@ import type {
import { QueryContext } from '~/queries/types'
import { AlertType } from 'products/alerts/frontend/types'
+import type { CohortRealtimeReadinessApi } from 'products/cohorts/frontend/generated/api.schemas'
import type { NodeApiSuspended, NodeEndpointApi } from 'products/data_modeling/frontend/generated/api.schemas'
import type {
DataWarehouseSavedQueryApi,
@@ -1924,6 +1925,9 @@ export interface CohortType {
filterTestAccounts?: boolean
}
experiment_set?: number[]
+ /** Whether feature flags can target this cohort, and the progress of the history build that
+ * gets it there. Null on projects the realtime pipeline does not cover. */
+ realtime?: CohortRealtimeReadinessApi | null
_create_in_folder?: string | null
_create_static_person_ids?: string[]
}
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 6d3c42029f12..da588d5e27b7 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -3,7 +3,7 @@ import json
import time
import uuid
import hashlib
-from collections.abc import Iterator
+from collections.abc import Iterator, Sequence
from copy import deepcopy
from typing import Annotated, Any, ClassVar, Literal, Optional, Union, cast
@@ -105,11 +105,19 @@ from products.cohorts.backend.models.util import (
validate_actors_query_for_cohort,
)
from products.cohorts.backend.models.validation import CohortTypeValidationSerializer
+from products.cohorts.backend.realtime_state import (
+ CohortHistoryBuildPhase,
+ CohortRealtimeReadiness,
+ CohortRealtimeState,
+ has_realtime_state,
+ resolve_realtime_readiness,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.team_feature_flags_config import (
PropertyMatchingVersion,
TeamFeatureFlagsConfig,
)
+from products.feature_flags.backend.realtime_targeting import is_realtime_cohort_flag_targeting_enabled
from products.product_analytics.backend.facade.models import Insight
@@ -673,6 +681,114 @@ class CohortConditionTypeField(serializers.JSONField):
pass
+# Carries the page's resolved readiness from the list serializer to each row's `get_realtime`.
+REALTIME_READINESS_CONTEXT_KEY = "realtime_readiness"
+# Caches the product flag's answer for the request, so a list page evaluates it once.
+REALTIME_TARGETING_ENABLED_CONTEXT_KEY = "realtime_targeting_enabled"
+
+
+def _team_from_serializer_context(context: dict[str, Any]) -> Optional[Team]:
+ """The team, from whichever context shape the caller provided.
+
+ The viewset passes a `get_team` lambda, experiments pass `team`, feature flag copy passes
+ `team_id`. Prefer an already-materialized object over the lambda, which can issue a query on
+ cold cache.
+ """
+ team = context.get("team")
+ if team is None and context.get("get_team"):
+ team = context["get_team"]()
+ if team is None and context.get("team_id"):
+ team = Team.objects.filter(pk=context["team_id"]).first()
+ return team
+
+
+def _realtime_targeting_enabled(context: dict[str, Any]) -> bool:
+ """Whether the request's user is in the realtime cohort flag targeting rollout.
+
+ Every realtime surface sits behind that product flag, and the API is the switch the frontend
+ reads, so `realtime` is null for everyone outside it. Cloud evaluates the flag locally in the
+ common case, but the helper is allowed to fall back to a remote call, so callers ask only
+ about cohorts a realtime state could describe. The answer is cached in the serializer context
+ so the list path pays it once per page.
+ """
+ if REALTIME_TARGETING_ENABLED_CONTEXT_KEY not in context:
+ request = context.get("request")
+ team = _team_from_serializer_context(context)
+ context[REALTIME_TARGETING_ENABLED_CONTEXT_KEY] = (
+ request is not None and team is not None and is_realtime_cohort_flag_targeting_enabled(request, team=team)
+ )
+ return context[REALTIME_TARGETING_ENABLED_CONTEXT_KEY]
+
+
+def _resolve_realtime_readiness_if_in_rollout(
+ cohorts: Sequence[Cohort], context: dict[str, Any]
+) -> dict[int, CohortRealtimeReadiness]:
+ """Readiness for the cohorts that have one, or an empty map.
+
+ Eligibility is checked before the rollout flag, and not after, so a project the pipeline does
+ not cover never pays for a flag evaluation that cannot change its answer.
+ """
+ relevant = [cohort for cohort in cohorts if has_realtime_state(cohort)]
+ if not relevant or not _realtime_targeting_enabled(context):
+ return {}
+ return resolve_realtime_readiness(relevant)
+
+
+class CohortHistoryBuildSerializer(serializers.Serializer):
+ phase = serializers.ChoiceField(
+ choices=CohortHistoryBuildPhase.choices,
+ help_text="What the build is doing now: `waiting` to start, `scanning` past events, or "
+ "`checking` the membership it produced. A build that is queued but has not started reports "
+ "`waiting` too.",
+ )
+ percent_complete = serializers.IntegerField(
+ allow_null=True,
+ help_text="How much of the event history has been scanned, 0 to 100. Null outside the "
+ "`scanning` phase, and while the scan is still being planned.",
+ )
+ updated_at = serializers.DateTimeField(
+ allow_null=True, help_text="When this build last made progress. Null while it is still queued."
+ )
+
+
+class CohortRealtimeReadinessSerializer(serializers.Serializer):
+ state = serializers.ChoiceField(
+ choices=CohortRealtimeState.choices,
+ help_text="Whether feature flags can target this cohort now. `ready`: they can, and they "
+ "see membership changes within about a minute. `building` / `rebuilding`: PostHog is "
+ "preparing the cohort from past events, and flags cannot target it yet. "
+ "`needs_attention`: the cohort qualifies but nothing is preparing it. `daily`: its "
+ "criteria are not supported in realtime, so its membership only comes from the once-a-day "
+ "calculation. `person_properties`: it matches on person properties, which flags read "
+ "directly, so they can always target it. `static`: it is a fixed list of people.",
+ )
+ ready_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="When the cohort became targetable by feature flags. Null unless the state is `ready`.",
+ )
+ build = CohortHistoryBuildSerializer(
+ allow_null=True,
+ help_text="The build preparing the cohort. Null unless the state is `building` or `rebuilding`.",
+ )
+
+
+class CohortListSerializer(serializers.ListSerializer):
+ """Resolves every row's realtime readiness once, instead of once per row.
+
+ Readiness reads backfill rows, so leaving it to the child serializer would put two queries on
+ each cohort of a page. This is the only hook DRF gives that sees the whole page.
+ """
+
+ def to_representation(self, data: Any) -> Any:
+ cohorts = list(data)
+ # `child` is only None before `many=True` binds one, which cannot happen during rendering.
+ assert self.child is not None
+ self.child.context[REALTIME_READINESS_CONTEXT_KEY] = _resolve_realtime_readiness_if_in_rollout(
+ cohorts, self.child.context
+ )
+ return super().to_representation(cohorts)
+
+
class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
earliest_timestamp_func = earliest_timestamp_func
@@ -695,9 +811,11 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
# If this cohort is an exposure cohort for an experiment
experiment_set: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField(many=True, read_only=True) # ty: ignore[invalid-assignment]
last_error_message = serializers.SerializerMethodField()
+ realtime = serializers.SerializerMethodField()
class Meta:
model = Cohort
+ list_serializer_class = CohortListSerializer
fields = [
"id",
"name",
@@ -721,6 +839,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
"is_static",
"cohort_type",
"condition_type",
+ "realtime",
"experiment_set",
"search_match_type",
"_create_in_folder",
@@ -742,6 +861,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
"last_import_unmatched_count",
"experiment_set",
"condition_type",
+ "realtime",
]
def __init__(self, *args: Any, **kwargs: Any) -> None:
@@ -756,10 +876,30 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
# cohorts that can't be evaluated locally. `last_error_message` is computed from
# a per-row correlated subquery over CohortCalculationHistory (see
# safely_get_queryset), and `experiment_set` costs a prefetch — basic-list callers
- # read neither, so drop them and skip the extra queries there.
+ # read neither, so drop them and skip the extra queries there. `realtime` stays: the
+ # flag picker and the flag condition chip read it off this payload, and it costs no
+ # query unless a page holds a realtime cohort whose build is in flight.
for field_name in ("query", "groups", "last_error_message", "experiment_set"):
self.fields.pop(field_name, None)
+ @extend_schema_field(
+ CohortRealtimeReadinessSerializer(
+ allow_null=True,
+ help_text="Whether feature flags can target this cohort, and the progress of the build "
+ "that gets it there. Null outside the realtime cohort flag targeting rollout, on projects "
+ "the realtime pipeline does not cover, and for cohorts that match on neither events nor "
+ "person properties, which nothing in the flag API decides on.",
+ )
+ )
+ def get_realtime(self, cohort: Cohort) -> Optional[dict[str, Any]]:
+ readiness = self.context.get(REALTIME_READINESS_CONTEXT_KEY)
+ if readiness is None:
+ # A single cohort — create, update, retrieve. The list path fills the context in
+ # `CohortListSerializer` so a page costs the same two queries as one row.
+ readiness = _resolve_realtime_readiness_if_in_rollout([cohort], self.context)
+ state = readiness.get(cohort.pk)
+ return CohortRealtimeReadinessSerializer(state).data if state is not None else None
+
def get_last_error_message(self, cohort: Cohort) -> Optional[str]:
# A static cohort is populated once, and nothing re-runs it afterwards, so the messages
# that promise an automatic retry must not reach one.
@@ -1181,16 +1321,8 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
return raw
def _team_for_warehouse_access_check(self) -> Optional[Team]:
- # Resolve the team from whichever context shape the caller provided so the check can't be
- # skipped: experiments pass "team", feature flag copy passes "team_id", the viewset passes
- # the get_team lambda. Prefer an already-materialized object over the lambda, which can
- # issue a query on cold cache.
- team = self.context.get("team")
- if team is None and self.context.get("get_team"):
- team = self.context["get_team"]()
- if team is None and self.context.get("team_id"):
- team = Team.objects.filter(pk=self.context["team_id"]).first()
- return team
+ # Resolved from whichever context shape the caller provided, so the check can't be skipped.
+ return _team_from_serializer_context(self.context)
def _validate_warehouse_access(self, attrs: dict) -> None:
"""Background execution runs the cohort without warehouse access control (the definition
@@ -1744,10 +1876,7 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
# When realtime cohort flag targeting is enabled, realtime cohorts that have been
# backfilled are allowed through.
if self.request.query_params.get("hide_behavioral_cohorts", "false").lower() == "true":
- # Avoid circular import: feature_flag imports cohort models
- from products.feature_flags.backend.api.feature_flag import _is_realtime_cohort_flag_targeting_enabled
-
- allow_realtime_backfilled = _is_realtime_cohort_flag_targeting_enabled(self.request, team=self.team)
+ allow_realtime_backfilled = is_realtime_cohort_flag_targeting_enabled(self.request, team=self.team)
# The flag's cohort typeahead hits this endpoint on every keystroke, so the
# behavioral set is computed once per team and cached (invalidated on cohort
# writes); see get_flag_excluded_behavioral_cohort_ids.
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index efe721619a55..b6db3a2a8498 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -34,6 +34,7 @@ from posthog.models.file_system.file_system import FileSystem
from posthog.models.person.util import get_person_by_id
from posthog.models.property import BehavioralPropertyType
from posthog.models.team.team import Team
+from posthog.redis import get_client as get_redis_client
from posthog.tasks.calculate_cohort import (
calculate_cohort_ch,
calculate_cohort_from_list,
@@ -45,8 +46,9 @@ from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.persons import create_person
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillTrigger
from products.cohorts.backend.models.cohort import Cohort, CohortType
-from products.cohorts.backend.models.dependencies import find_behavioral_cohorts
+from products.cohorts.backend.models.dependencies import cohort_backfill_pending_key, find_behavioral_cohorts
from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_ids
from products.exports.backend.api.test.test_exports import TestExportMixin
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -2023,8 +2025,9 @@ [email protected],
# `filters` stays: the feature-flag intent warning reads it off the basic list to flag
# behavioral cohorts. `is_calculating` drives the 5s repoll and `is_static` drives the
# static-cohort flag warning — both now read only from the basic payload, so trimming
- # any of these silently breaks a feature. Guard them here.
- for kept in ("id", "name", "count", "filters", "is_calculating", "is_static"):
+ # any of these silently breaks a feature. `realtime` feeds the flag picker's cohort rows
+ # and the condition chip. Guard them here.
+ for kept in ("id", "name", "count", "filters", "is_calculating", "is_static", "realtime"):
self.assertIn(kept, basic)
@patch("posthog.api.cohort.report_user_action")
@@ -2053,6 +2056,87 @@ [email protected],
self.assertNotIn("posthog_cohortcalculationhistory", basic_sql)
self.assertNotIn("posthog_experiment", basic_sql)
+ @patch("posthog.api.cohort.is_realtime_cohort_flag_targeting_enabled")
+ @patch("posthog.api.cohort.report_user_action")
+ def test_realtime_readiness_is_served_only_where_the_pipeline_runs(self, patch_capture, mock_flag_enabled):
+ # The wiring guard for the derived state: a realtime team in the rollout gets it on both the
+ # list and the detail response, and every other team, and every user outside the rollout,
+ # gets null rather than a state its flags can't read.
+ mock_flag_enabled.return_value = True
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="realtime cohort",
+ cohort_type=CohortType.REALTIME,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {"type": "behavioral", "key": "$pageview", "event_type": "events", "value": "performed_event"}
+ ],
+ }
+ },
+ )
+
+ with self.settings(REALTIME_COHORT_TEAM_ALLOWLIST="all"):
+ detail = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort.id}/").json()
+ listed = self.client.get(f"/api/projects/{self.team.id}/cohorts").json()["results"][0]
+ # The basic payload is what `cohortsById` is built from, so it is where the flag
+ # picker's rows and the condition link's bolt read the state.
+ basic = self.client.get(f"/api/projects/{self.team.id}/cohorts?basic=true").json()["results"][0]
+ self.assertEqual(detail["realtime"]["state"], "needs_attention")
+ self.assertEqual(listed["realtime"]["state"], "needs_attention")
+ self.assertEqual(basic["realtime"]["state"], "needs_attention")
+
+ with self.settings(REALTIME_COHORT_TEAM_ALLOWLIST="none"):
+ detail = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort.id}/").json()
+ self.assertIsNone(detail["realtime"])
+
+ mock_flag_enabled.return_value = False
+ with self.settings(REALTIME_COHORT_TEAM_ALLOWLIST="all"):
+ detail = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort.id}/").json()
+ listed = self.client.get(f"/api/projects/{self.team.id}/cohorts").json()["results"][0]
+ self.assertIsNone(detail["realtime"])
+ self.assertIsNone(listed["realtime"])
+
+ @patch("posthog.api.cohort.is_realtime_cohort_flag_targeting_enabled")
+ @patch("posthog.api.cohort.report_user_action")
+ def test_realtime_readiness_is_resolved_once_for_a_whole_list_page(self, patch_capture, mock_flag_enabled):
+ # `CohortListSerializer` is the only thing that makes this per page rather than per row, and
+ # dropping it changes no JSON: `get_realtime` falls back to resolving the row on its own. The
+ # flag picker's cohort typeahead hits this endpoint on every keystroke.
+ mock_flag_enabled.return_value = True
+ behavioral_filters = {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {"type": "behavioral", "key": "$pageview", "event_type": "events", "value": "performed_event"}
+ ],
+ }
+ }
+ # Two cohorts mid-build, or per row and per page are the same number. A debounce key is the
+ # cheapest way to put a cohort in that state, with no backfill run to set up.
+ for index in range(2):
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name=f"realtime cohort {index}",
+ cohort_type=CohortType.REALTIME,
+ filters=behavioral_filters,
+ )
+ get_redis_client().set(
+ cohort_backfill_pending_key(cohort.id, CohortBackfillKind.BEHAVIORAL),
+ CohortBackfillTrigger.COHORT_CREATED,
+ ex=300,
+ )
+
+ with self.settings(REALTIME_COHORT_TEAM_ALLOWLIST="all"):
+ with capture_db_queries() as ctx:
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts").json()
+
+ self.assertEqual([row["realtime"]["state"] for row in response["results"]], ["building", "building"])
+ # Counting the queries that touch the participation table, not substrings of one joined
+ # string: Django qualifies every selected column with the table name.
+ self.assertEqual(sum("cohort_backfill_run_cohorts" in query["sql"] for query in ctx.captured_queries), 1)
+
@patch("posthog.api.cohort.report_user_action")
def test_basic_is_ignored_on_detail_fetch(self, patch_capture):
# `basic` only trims the list. A detail fetch must keep `filters` so the
@@ -2207,7 +2291,7 @@ [email protected],
("realtime_backfilled_flag_off", CohortType.REALTIME, True, False, False),
]
)
- @patch("products.feature_flags.backend.api.feature_flag._is_realtime_cohort_flag_targeting_enabled")
+ @patch("posthog.api.cohort.is_realtime_cohort_flag_targeting_enabled")
@patch("posthog.api.cohort.report_user_action")
def test_behavioral_cohort_dropdown_visibility(
self,
@@ -2264,7 +2348,7 @@ [email protected],
else:
self.assertNotIn(behavioral_cohort.id, result_ids)
- @patch("products.feature_flags.backend.api.feature_flag._is_realtime_cohort_flag_targeting_enabled")
+ @patch("posthog.api.cohort.is_realtime_cohort_flag_targeting_enabled")
@patch("posthog.api.cohort.report_user_action")
def test_nested_cohort_with_flag_compatible_leaf_visible_when_flag_on(
self,
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index 1be787fc9b08..f8b043af8b61 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -513,6 +513,7 @@
'_maintain_filter_shape_hashes',
'_meta',
'_person_shape_changed',
+ '_required_backfill_stamps',
'_safe_reset_calculating_state',
'_safe_save_cohort_state',
'backfill_participations',
@@ -552,6 +553,7 @@
'people',
'person_filters_shape_hash',
'properties',
+ 'realtime_ready_at',
'remove_user_by_uuid',
'save',
'team_id',
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 2f23a1635914..82f9fae114b0 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -35,6 +35,7 @@ from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.schema_enums import ProductKey
from posthog.settings.base_variables import TEST
+from products.cohorts.backend.models.backfill import CohortBackfillKind
from products.cohorts.backend.models.leaf_shape import (
FilterShapeHashes,
extract_behavioral_leaf_shape_hash,
@@ -573,33 +574,50 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
"cohorts": any(leaf.get("type") == "cohort" for leaf in leaves),
}
+ def _required_backfill_stamps(self) -> dict[str, Optional[datetime]]:
+ """The backfill stamp each of this cohort's current filter kinds needs, keyed by that kind.
+
+ The one place the filter-type-to-stamp mapping lives, so `is_flag_compatible`,
+ `realtime_ready_at` and the realtime state resolver cannot drift apart. A third gated leaf
+ kind added to one of them and not the others would let a cohort read as ready from a
+ backfill its filters never needed.
+
+ Empty when no filter type is recognized (empty filters, cohort-reference-only, and so on):
+ the realtime evaluator has no leaf to key membership on, so stale stamps mean nothing.
+ """
+ stamps: dict[str, Optional[datetime]] = {}
+ if self._has_filter_type("person") or self._has_filter_type("person_metadata"):
+ stamps[CohortBackfillKind.PERSON_PROPERTY.value] = self.last_backfill_person_properties_at
+ if self._has_filter_type("behavioral"):
+ stamps[CohortBackfillKind.BEHAVIORAL.value] = self.last_backfill_events_at
+ return stamps
+
@property
def is_flag_compatible(self) -> bool:
"""Whether this cohort can be used in feature flag targeting via cohort_membership lookups.
- Gates on both person property and event backfills based on which filter types the cohort uses:
- - Cohorts with person property or person_metadata filters require last_backfill_person_properties_at
- - Cohorts with behavioral event filters require last_backfill_events_at
- - Cohorts with both require both timestamps
- - Cohorts with neither recognized filter type (empty filters, cohort-reference-only, etc.)
- are not flag-compatible, even if stale timestamps are set, because the realtime
- evaluator has no leaf to key membership on.
+ Every backfill its current filters need has to have landed: person property and
+ person_metadata filters need `last_backfill_person_properties_at`, behavioral event filters
+ need `last_backfill_events_at`, and a cohort with both needs both.
"""
if self.cohort_type != CohortType.REALTIME:
return False
- has_person_filters = self._has_filter_type("person") or self._has_filter_type("person_metadata")
- has_behavioral_filters = self._has_filter_type("behavioral")
-
- if not (has_person_filters or has_behavioral_filters):
- return False
+ stamps = self._required_backfill_stamps()
+ return bool(stamps) and all(stamp is not None for stamp in stamps.values())
- if has_person_filters and self.last_backfill_person_properties_at is None:
- return False
- if has_behavioral_filters and self.last_backfill_events_at is None:
- return False
+ @property
+ def realtime_ready_at(self) -> Optional[datetime]:
+ """When this cohort became targetable by feature flags, or None while it isn't.
- return True
+ The later of the stamps `is_flag_compatible` gates on, and only those: a cohort can carry a
+ stamp for a leaf kind its filters no longer use, and reporting that one would date the
+ readiness to a backfill the current definition never needed.
+ """
+ if not self.is_flag_compatible:
+ return None
+ # `is_flag_compatible` has already proved every required stamp is set.
+ return max(stamp for stamp in self._required_backfill_stamps().values() if stamp is not None)
@property
def properties(self) -> PropertyGroup:
diff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.py
index d25ad719a7d8..02b5e47276f0 100644
--- a/products/cohorts/backend/models/dependencies.py
+++ b/products/cohorts/backend/models/dependencies.py
@@ -41,6 +41,16 @@ COHORT_BACKFILL_DEBOUNCE_SECONDS = 300 # 5 minutes
# than the countdown would swallow a save that lands after the task already read its state.
COHORT_BACKFILL_REDIS_TTL_SECONDS = COHORT_BACKFILL_DEBOUNCE_SECONDS
+
+def cohort_backfill_pending_key(cohort_id: int, kind: str) -> str:
+ """The debounce key for one cohort and kind, holding the pending task's trigger kind.
+
+ It is the only record that a save asked for a build during the countdown, so the cohort API
+ reads it to tell a queued build from a cohort nothing is building.
+ """
+ return f"cohort_backfill_{kind}_pending:{cohort_id}"
+
+
# Prometheus metrics for cache hit/miss tracking
COHORT_DEPENDENCY_CACHE_COUNTER = Counter(
"posthog_cohort_dependency_cache_requests_total",
@@ -496,8 +506,8 @@ def _trigger_cohort_backfill(cohort: Cohort, trigger_kind: str, kind: CohortBack
)
redis_client = get_redis_client()
- lock_key = f"cohort_backfill_{kind}_pending:{cohort.pk}"
- if not redis_client.set(lock_key, 1, nx=True, ex=COHORT_BACKFILL_REDIS_TTL_SECONDS):
+ lock_key = cohort_backfill_pending_key(cohort.pk, kind)
+ if not redis_client.set(lock_key, trigger_kind, nx=True, ex=COHORT_BACKFILL_REDIS_TTL_SECONDS):
COHORT_BACKFILL_TRIGGER_COUNTER.labels(backfill_kind=kind, outcome="debounced").inc()
logger.info(
"cohort_backfill_already_pending",
diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
index e2930042334e..baacb87b6db4 100644
--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
@@ -330,7 +330,11 @@ class TestBehavioralBackfillDependencies(BaseTest):
args=[self.team.id, cohort.id, "cohort_edited", kind],
countdown=300,
)
- redis.set.assert_called_once_with(f"cohort_backfill_{kind.value}_pending:{cohort.id}", 1, nx=True, ex=300)
+ # The value is the pending task's trigger kind, which the cohort API reads to show a build
+ # as queued during the countdown, before any run row exists.
+ redis.set.assert_called_once_with(
+ f"cohort_backfill_{kind.value}_pending:{cohort.id}", "cohort_edited", nx=True, ex=300
+ )
@parameterized.expand(
[
@@ -547,9 +551,11 @@ class TestBehavioralBackfillDependencies(BaseTest):
args=[self.team.id, cohort.id, "cohort_edited", kind],
countdown=300,
)
+ # The value is the pending task's trigger kind, which the cohort API reads to show a build
+ # as queued during the countdown, before any run row exists.
self.assertEqual(
redis.set.call_args_list,
- [mock.call(f"cohort_backfill_{kind.value}_pending:{cohort.id}", 1, nx=True, ex=300)] * 2,
+ [mock.call(f"cohort_backfill_{kind.value}_pending:{cohort.id}", "cohort_edited", nx=True, ex=300)] * 2,
)
@parameterized.expand(
diff --git a/products/cohorts/backend/realtime_state.py b/products/cohorts/backend/realtime_state.py
new file mode 100644
index 000000000000..bb63843ec314
--- /dev/null
+++ b/products/cohorts/backend/realtime_state.py
@@ -0,0 +1,426 @@
+"""The one realtime state a cohort shows a reader, derived from the pipeline's several truths.
+
+Django's ``is_flag_compatible``, the backfill run row, and the realtime team allowlist each answer a
+different question, and none of them is the answer a person wants ("can a feature flag target this
+cohort right now"). This module collapses them into one state plus, while the cohort is being
+prepared, that build's progress.
+
+Only a cohort whose criteria decide the answer gets a state: one with event-based criteria, which
+a backfill has to prepare before flags can read it, and one that matches on person properties,
+which flags read straight off the person and can therefore always target. A cohort with neither
+gets no state, so nothing claims an answer the flag API does not enforce.
+
+Every state comes from a row that exists, and from one per backfill kind the cohort needs. A kind
+whose backfill was refused, lost, or never triggered has no run and no queued task, so the cohort
+reads as ``needs_attention`` and never as ``building``, however well its other kind is going: the
+filters changing is not evidence that anything is rebuilding.
+"""
+
+from collections import defaultdict
+from collections.abc import Iterable, Sequence
+from datetime import datetime
+from typing import Any, TypeGuard
+from uuid import UUID
+
+from django.db import models
+from django.db.models import Count, Max, Q
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.redis import get_client as get_redis_client
+
+from products.cohorts.backend.models.backfill import (
+ ACTIVE_COHORT_BACKFILL_RUN_STATUSES,
+ CohortBackfillChunk,
+ CohortBackfillChunkStatus,
+ CohortBackfillRun,
+ CohortBackfillRunCohort,
+ CohortBackfillRunStatus,
+ CohortBackfillTrigger,
+)
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+from products.cohorts.backend.models.dependencies import cohort_backfill_pending_key
+from products.cohorts.backend.realtime_teams import is_realtime_cohort_team
+
+logger = structlog.get_logger(__name__)
+
+
+class CohortRealtimeState(models.TextChoices):
+ STATIC = "static", "Static"
+ PERSON_PROPERTIES = "person_properties", "Person properties"
+ DAILY = "daily", "Daily"
+ BUILDING = "building", "Building"
+ REBUILDING = "rebuilding", "Rebuilding"
+ READY = "ready", "Ready"
+ NEEDS_ATTENTION = "needs_attention", "Needs attention"
+
+
+class CohortHistoryBuildPhase(models.TextChoices):
+ WAITING = "waiting", "Waiting"
+ SCANNING = "scanning", "Scanning"
+ CHECKING = "checking", "Checking"
+
+
+# The run statuses a build shows a phase for. `blocked` is active but parked on an operator
+# attestation, and every terminal status is either done or a failure, so both resolve to a state
+# instead. Exhaustive on purpose: a ninth run status has to be placed here deliberately rather than
+# fall through to a phase that would misdescribe it.
+_PHASE_BY_RUN_STATUS: dict[str, CohortHistoryBuildPhase] = {
+ CohortBackfillRunStatus.AWAITING_BOUNDARY: CohortHistoryBuildPhase.WAITING,
+ CohortBackfillRunStatus.SEEDING: CohortHistoryBuildPhase.SCANNING,
+ CohortBackfillRunStatus.RECONCILING: CohortHistoryBuildPhase.CHECKING,
+}
+
+# Least to most advanced. A cohort waiting on two kinds is only as far along as its slowest one.
+_PHASE_RANK: dict[str, int] = {
+ CohortHistoryBuildPhase.WAITING: 0,
+ CohortHistoryBuildPhase.SCANNING: 1,
+ CohortHistoryBuildPhase.CHECKING: 2,
+}
+
+
+def _has_phase(run: CohortBackfillRun | None) -> TypeGuard[CohortBackfillRun]:
+ """Whether a live run is far enough along to describe a build phase."""
+ return run is not None and run.status in _PHASE_BY_RUN_STATUS
+
+
+@frozen
+class CohortHistoryBuild:
+ """The run building one cohort's history, as much of it as a reader needs."""
+
+ phase: str
+ percent_complete: int | None
+ updated_at: datetime | None
+
+
+@frozen
+class CohortRealtimeReadiness:
+ """What one cohort can be used for right now."""
+
+ state: str
+ ready_at: datetime | None
+ build: CohortHistoryBuild | None
+
+
+def _has_event_criteria(cohort: Cohort) -> bool:
+ """Whether the cohort matches on events, counting the ones that store that in ``groups``.
+
+ ``_has_filter_type`` walks the ``filters`` JSON alone, and a legacy cohort keeps its condition
+ in the deprecated ``groups`` field instead, where ``Cohort.properties`` is what turns an
+ ``action_id`` or ``event_id`` entry into a behavioral property. The flag API refuses a cohort
+ on either signal, so both have to reach this module as well, or such a cohort would read as one
+ flags can target and then be refused on save. ``groups`` is only parsed when ``filters`` is
+ empty, which is the one case ``Cohort.properties`` reads it at all, so a modern cohort pays
+ nothing for the second test.
+ """
+ if cohort._has_filter_type("behavioral"):
+ return True
+ return not cohort.filters and any(prop.type == "behavioral" for prop in cohort.properties.flat)
+
+
+def _has_person_criteria(cohort: Cohort) -> bool:
+ """Whether the cohort matches on person properties, which feature flags read directly."""
+ return cohort._has_filter_type("person") or cohort._has_filter_type("person_metadata")
+
+
+def _settled_state(cohort: Cohort) -> str | None:
+ """The state a cohort has without consulting a run row, or None when a run decides it."""
+ if cohort.is_static:
+ return CohortRealtimeState.STATIC
+ if not _has_event_criteria(cohort):
+ # Flags evaluate person properties off the person record as they run, so they can target
+ # this cohort whatever the pipeline is doing. Only an event-based leaf waits on a backfill.
+ return CohortRealtimeState.PERSON_PROPERTIES
+ if cohort.cohort_type != CohortType.REALTIME:
+ return CohortRealtimeState.DAILY
+ if cohort.is_flag_compatible:
+ return CohortRealtimeState.READY
+ return None
+
+
+def _required_backfill_kinds(cohort: Cohort) -> set[str]:
+ """The backfill kinds this cohort's current filters need stamped before flags can target it.
+
+ The same mapping `is_flag_compatible` gates on. A cohort can still be participating in an
+ active run for a kind its filters no longer use, and that run decides nothing about it.
+ """
+ return set(cohort._required_backfill_stamps())
+
+
+def _percent_complete(chunks: dict[str, Any] | None) -> int | None:
+ """Scan progress as a whole percent, or None while the run has planned no chunks.
+
+ Rounded down, so 100 means every chunk is confirmed rather than 199 of 200.
+ """
+ if not chunks or not chunks["chunks_total"]:
+ return None
+ return chunks["chunks_confirmed"] * 100 // chunks["chunks_total"]
+
+
+def _active_participations_per_cohort(
+ team_id: int, cohort_ids: Sequence[int], *, statuses: Iterable[str]
+) -> dict[int, list[CohortBackfillRunCohort]]:
+ """Every live participation per cohort among ``statuses``, newest run first.
+
+ Participations are the per-cohort lens: a team-scoped run carries no ``cohort_id`` of its own,
+ so reading runs directly would miss every cohort a team enablement run is building.
+
+ A superseded participation is dropped even though its run is still active. Editing a cohort
+ that a team run is building supersedes only its participation, and reading that row would
+ report the abandoned build instead of the rebuild the edit just asked for.
+
+ One cohort can hold several at once, one per backfill kind, so the caller combines them rather
+ than taking the newest: a cohort is ready only once every kind it needs has finished.
+ """
+ participations = (
+ # `Cohort` is a RootTeamMixin, so a cohort's team id is already the project's canonical
+ # team: resolving it again would put a `posthog_team` read on every cohort request.
+ CohortBackfillRunCohort.objects.for_team(team_id, canonical=True)
+ .filter(cohort_id__in=cohort_ids, superseded_at__isnull=True, run__status__in=statuses)
+ .select_related("run")
+ # Both rows carry JSON columns wide enough to dwarf the request: the run's `pinned` holds
+ # the catalog of every cohort it is building, and a page repeats that row per cohort.
+ .only(
+ "cohort_id",
+ "run__status",
+ "run__trigger_kind",
+ "run__backfill_kind",
+ "run__created_at",
+ "run__updated_at",
+ )
+ .order_by("cohort_id", "-run__created_at")
+ )
+ by_cohort: dict[int, list[CohortBackfillRunCohort]] = defaultdict(list)
+ for participation in participations:
+ by_cohort[participation.cohort_id].append(participation)
+ return by_cohort
+
+
+def _queued_triggers(pairs: Sequence[tuple[int, str]]) -> dict[tuple[int, str], str] | None:
+ """The trigger kind of the debounced run-creation task for each cohort and backfill kind asked for.
+
+ A save enqueues that task with a five-minute countdown, so for those five minutes the debounce
+ key is the only record that a build was asked for. Without it, every cohort would read as
+ `needs_attention` for the first five minutes after the edit that is about to rebuild it.
+
+ Returns None when the lookup itself failed, which is not the same answer as "no task is
+ queued": the caller reports no state at all rather than asserting that nothing is preparing
+ these cohorts.
+ """
+ if not pairs:
+ # redis-py sends an argument-less MGET rather than short-circuiting, and the server
+ # answers with an error that `parse_response` turns into an empty list. Every build that
+ # is already running takes this path, and that is when the detail endpoint is polled.
+ return {}
+
+ keys = [cohort_backfill_pending_key(cohort_id, kind) for cohort_id, kind in pairs]
+ try:
+ values = get_redis_client().mget(keys)
+ except Exception as error:
+ # Saying nothing is a better failure than a wrong state, and than a cohort list that 500s.
+ logger.warning("cohort_backfill_pending_lookup_failed", error=str(error))
+ return None
+
+ return {
+ pair: (value.decode() if isinstance(value, bytes) else str(value))
+ for pair, value in zip(pairs, values, strict=True)
+ if value is not None
+ }
+
+
+def _chunk_tallies(team_id: int, run_ids: Sequence[UUID]) -> dict[UUID, dict[str, Any]]:
+ if not run_ids:
+ return {}
+ tallies = (
+ CohortBackfillChunk.objects.for_team(team_id, canonical=True)
+ .filter(run_id__in=run_ids)
+ .values("run_id")
+ .annotate(
+ chunks_total=Count("id"),
+ chunks_confirmed=Count("id", filter=Q(status=CohortBackfillChunkStatus.CONFIRMED)),
+ # A chunk finishing does not touch the run row, so the run's own `updated_at` can sit
+ # still for hours while the percentage climbs.
+ chunks_updated_at=Max("updated_at"),
+ )
+ )
+ return {tally["run_id"]: tally for tally in tallies}
+
+
+@frozen
+class _KindProgress:
+ """How one backfill kind of one cohort is coming along, from a run row or from a queued task."""
+
+ phase: str
+ trigger: str
+ run: CohortBackfillRun | None
+
+
+def _live_run_per_kind(
+ participations: Sequence[CohortBackfillRunCohort], required_kinds: set[str]
+) -> dict[str, CohortBackfillRun]:
+ """The newest live run per backfill kind, among the kinds a cohort's current filters still need.
+
+ A cohort can hold two live participations of one kind at once, its own run and the team's, and
+ it can hold participations for a kind its filters no longer use, which decide nothing about it.
+ """
+ per_kind: dict[str, CohortBackfillRun] = {}
+ for participation in participations: # newest run first
+ kind = participation.run.backfill_kind
+ if kind in required_kinds and kind not in per_kind:
+ per_kind[kind] = participation.run
+ return per_kind
+
+
+def _cohort_progress(
+ cohort_id: int,
+ required_kinds: set[str],
+ live_runs: dict[str, CohortBackfillRun],
+ queued: dict[tuple[int, str], str],
+) -> list[_KindProgress] | None:
+ """One progress record per required backfill kind, or None when nothing is building the cohort.
+
+ A cohort is ready only once every kind its filters need has finished, so every one of them has
+ to be moving for the cohort to read as a build in progress. One kind seeding while the other
+ was refused, lost or never triggered is a cohort nothing is carrying to ready, and reporting it
+ as preparing would leave a progress bar running against a build that is not coming.
+
+ A run that has started outranks the debounce key for its kind: the key survives until the
+ countdown it was set for expires, so both records exist for as long as the task takes to run.
+ """
+ progress: list[_KindProgress] = []
+ for kind in sorted(required_kinds):
+ run = live_runs.get(kind)
+ if _has_phase(run):
+ progress.append(_KindProgress(phase=_PHASE_BY_RUN_STATUS[run.status], trigger=run.trigger_kind, run=run))
+ continue
+ trigger = queued.get((cohort_id, kind))
+ if trigger is None:
+ return None
+ progress.append(_KindProgress(phase=CohortHistoryBuildPhase.WAITING, trigger=trigger, run=None))
+ return progress or None
+
+
+def _resolve_for_team(team_id: int, cohorts: Sequence[Cohort]) -> dict[int, CohortRealtimeReadiness]:
+ readiness: dict[int, CohortRealtimeReadiness] = {}
+ pending: list[Cohort] = []
+
+ for cohort in cohorts:
+ settled = _settled_state(cohort)
+ if settled is None:
+ pending.append(cohort)
+ else:
+ readiness[cohort.id] = CohortRealtimeReadiness(
+ # Only a prepared realtime cohort has a moment it became targetable. A person
+ # property cohort always was, and it can carry a stamp from an earlier definition.
+ state=settled,
+ ready_at=cohort.realtime_ready_at if settled == CohortRealtimeState.READY else None,
+ build=None,
+ )
+
+ if not pending:
+ return readiness
+
+ participations = _active_participations_per_cohort(
+ team_id, [cohort.id for cohort in pending], statuses=ACTIVE_COHORT_BACKFILL_RUN_STATUSES
+ )
+ required_kinds = {cohort.id: _required_backfill_kinds(cohort) for cohort in pending}
+ live_runs = {
+ cohort.id: _live_run_per_kind(participations.get(cohort.id, []), required_kinds[cohort.id])
+ for cohort in pending
+ }
+
+ # A kind whose live run has a phase is progressing on its own evidence. Every other required
+ # kind has to be found in the debounce key: a run parked on an operator (`blocked`) has no
+ # phase, and a kind with no live run at all may still have a task waiting out its countdown.
+ # Asking about nothing else keeps a page whose builds are all running free of a round trip.
+ unresolved = {
+ cohort.id: {kind for kind in required_kinds[cohort.id] if not _has_phase(live_runs[cohort.id].get(kind))}
+ for cohort in pending
+ }
+ queued = _queued_triggers([(cohort.id, kind) for cohort in pending for kind in sorted(unresolved[cohort.id])])
+
+ progress_by_cohort: dict[int, list[_KindProgress]] = {}
+ for cohort in pending:
+ if queued is None and unresolved[cohort.id]:
+ # The lookup that would say whether a build is queued is unavailable, so this cohort
+ # gets no state rather than one asserting that nothing is preparing it.
+ continue
+ progress = _cohort_progress(cohort.id, required_kinds[cohort.id], live_runs[cohort.id], queued or {})
+ if progress is None:
+ readiness[cohort.id] = CohortRealtimeReadiness(
+ state=CohortRealtimeState.NEEDS_ATTENTION, ready_at=None, build=None
+ )
+ continue
+ progress_by_cohort[cohort.id] = progress
+
+ # A cohort is only as far along as its least advanced kind, and that is the only run a reader
+ # is shown, so it is the only one whose chunks are tallied.
+ slowest_by_cohort = {
+ cohort_id: min(progress, key=lambda item: _PHASE_RANK[item.phase])
+ for cohort_id, progress in progress_by_cohort.items()
+ }
+ chunks_by_run = _chunk_tallies(
+ team_id, [item.run.id for item in slowest_by_cohort.values() if item.run is not None]
+ )
+
+ for cohort_id, slowest in slowest_by_cohort.items():
+ chunks = chunks_by_run.get(slowest.run.id) if slowest.run is not None else None
+ timestamps = (
+ slowest.run.updated_at if slowest.run is not None else None,
+ chunks["chunks_updated_at"] if chunks else None,
+ )
+ readiness[cohort_id] = CohortRealtimeReadiness(
+ state=(
+ CohortRealtimeState.REBUILDING
+ # Any required kind's build being an edit makes the whole thing a rebuild: both
+ # kinds are asked for together, and the edit is the one with a consequence for flags.
+ if any(
+ progress.trigger == CohortBackfillTrigger.COHORT_EDITED
+ for progress in progress_by_cohort[cohort_id]
+ )
+ else CohortRealtimeState.BUILDING
+ ),
+ ready_at=None,
+ build=CohortHistoryBuild(
+ phase=slowest.phase,
+ # Chunks are the scan's own unit of work, so they measure no other phase: a
+ # reconciling run has confirmed all of them, and a bar at 100% under "checking"
+ # would read as a build that has finished and stalled.
+ percent_complete=(
+ _percent_complete(chunks) if slowest.phase == CohortHistoryBuildPhase.SCANNING else None
+ ),
+ updated_at=max((stamp for stamp in timestamps if stamp is not None), default=None),
+ ),
+ )
+
+ return readiness
+
+
+def has_realtime_state(cohort: Cohort) -> bool:
+ """Whether this cohort can have a flag targeting state at all.
+
+ False on a team that does not run the pipeline, because its flags can never read realtime
+ membership, and for a cohort whose criteria are neither event-based nor person properties: a
+ cohort reference alone leaves the realtime evaluator no leaf to key membership on, and nothing
+ in the flag API turns on it either. Neither has anything to say, so neither pays for the run
+ lookups, or the rollout flag evaluation, that saying it costs.
+
+ In-memory only: the allowlist is a parsed setting and the criteria come off the cohort row.
+ """
+ if cohort.pk is None or not is_realtime_cohort_team(cohort.team_id):
+ return False
+ return _has_event_criteria(cohort) or _has_person_criteria(cohort)
+
+
+def resolve_realtime_readiness(cohorts: Sequence[Cohort]) -> dict[int, CohortRealtimeReadiness]:
+ """One readiness per cohort id, for the cohorts ``has_realtime_state`` admits."""
+ by_team: dict[int, list[Cohort]] = defaultdict(list)
+ for cohort in cohorts:
+ if has_realtime_state(cohort):
+ by_team[cohort.team_id].append(cohort)
+
+ readiness: dict[int, CohortRealtimeReadiness] = {}
+ for team_id, team_cohorts in by_team.items():
+ readiness.update(_resolve_for_team(team_id, team_cohorts))
+ return readiness
diff --git a/products/cohorts/backend/test/test_realtime_state.py b/products/cohorts/backend/test/test_realtime_state.py
new file mode 100644
index 000000000000..7ff54360d4e8
--- /dev/null
+++ b/products/cohorts/backend/test/test_realtime_state.py
@@ -0,0 +1,438 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.redis import get_client as get_redis_client
+
+from products.cohorts.backend.models.backfill import (
+ CohortBackfillChunk,
+ CohortBackfillChunkStatus,
+ CohortBackfillKind,
+ CohortBackfillRun,
+ CohortBackfillRunCohort,
+ CohortBackfillRunStatus,
+ CohortBackfillScope,
+ CohortBackfillTrigger,
+)
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+from products.cohorts.backend.models.dependencies import cohort_backfill_pending_key
+from products.cohorts.backend.realtime_state import (
+ CohortHistoryBuildPhase,
+ CohortRealtimeState,
+ resolve_realtime_readiness,
+)
+
+BEHAVIORAL_LEAF: dict = {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event",
+ "time_value": 7,
+ "time_interval": "day",
+}
+
+PERSON_LEAF: dict = {"type": "person", "key": "email", "value": ["[email protected]"], "operator": "exact"}
+
+COHORT_LEAF: dict = {"type": "cohort", "key": "id", "value": 1}
+
+
+def filters(*leaves: dict) -> dict:
+ return {"properties": {"type": "AND", "values": list(leaves)}}
+
+
+@override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="all")
+class TestRealtimeReadiness(BaseTest):
+ def _cohort(self, **kwargs) -> Cohort:
+ defaults = {"team": self.team, "cohort_type": CohortType.REALTIME, "filters": filters(BEHAVIORAL_LEAF)}
+ return Cohort.objects.create(**{**defaults, **kwargs})
+
+ def _run(
+ self,
+ *,
+ status: str = CohortBackfillRunStatus.SEEDING,
+ trigger: str = CohortBackfillTrigger.COHORT_CREATED,
+ scope: str = CohortBackfillScope.COHORT,
+ kind: str = CohortBackfillKind.BEHAVIORAL,
+ cohort: Cohort | None = None,
+ created_at=None,
+ ) -> CohortBackfillRun:
+ run = CohortBackfillRun.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ cohort=cohort if scope == CohortBackfillScope.COHORT else None,
+ backfill_kind=kind,
+ trigger_kind=trigger,
+ scope=scope,
+ status=status,
+ timezone="UTC",
+ )
+ if created_at is not None:
+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(created_at=created_at)
+ run.refresh_from_db()
+ return run
+
+ def _participate(self, run: CohortBackfillRun, cohort: Cohort) -> CohortBackfillRunCohort:
+ return CohortBackfillRunCohort.objects.for_team(self.team.id).create(
+ run=run, team_id=self.team.id, cohort=cohort, filters_shape_hash="shape", pinned_filters=cohort.filters
+ )
+
+ def _chunks(self, run: CohortBackfillRun, *, total: int, confirmed: int) -> None:
+ for index in range(total):
+ CohortBackfillChunk.objects.for_team(self.team.id).create(
+ run=run,
+ team_id=self.team.id,
+ day=timezone.now().date() - timedelta(days=index),
+ status=(
+ CohortBackfillChunkStatus.CONFIRMED if index < confirmed else CohortBackfillChunkStatus.PENDING
+ ),
+ )
+
+ def _state(self, cohort: Cohort) -> str | None:
+ readiness = resolve_realtime_readiness([cohort]).get(cohort.id)
+ return readiness.state if readiness else None
+
+ def test_unstamped_cohort_with_no_run_needs_attention_rather_than_building(self) -> None:
+ # The whole point of deriving from a run row: a refused, lost, or never-triggered backfill
+ # must not read as work in progress, or the progress bar never ends.
+ assert self._state(self._cohort()) == CohortRealtimeState.NEEDS_ATTENTION
+
+ @parameterized.expand(
+ [
+ # The keys are set with `nx=True` and each kind has its own handler, so a cohort
+ # created with one leaf kind and edited to add the other inside the five-minute
+ # countdown carries a different trigger per kind. The edit is the one that decides.
+ (
+ "created",
+ {CohortBackfillKind.BEHAVIORAL: CohortBackfillTrigger.COHORT_CREATED},
+ CohortRealtimeState.BUILDING,
+ ),
+ (
+ "edited",
+ {CohortBackfillKind.BEHAVIORAL: CohortBackfillTrigger.COHORT_EDITED},
+ CohortRealtimeState.REBUILDING,
+ ),
+ (
+ "created_then_edited",
+ {
+ CohortBackfillKind.BEHAVIORAL: CohortBackfillTrigger.COHORT_CREATED,
+ CohortBackfillKind.PERSON_PROPERTY: CohortBackfillTrigger.COHORT_EDITED,
+ },
+ CohortRealtimeState.REBUILDING,
+ ),
+ ]
+ )
+ def test_debounced_save_reads_as_a_build_before_its_run_exists(
+ self, _name: str, triggers: dict[str, str], expected: str
+ ) -> None:
+ # The run-creation task waits five minutes. Without the debounce key, every cohort would
+ # read as needs_attention for those five minutes, right after the save that asked for it.
+ leaves = [BEHAVIORAL_LEAF] + ([PERSON_LEAF] if len(triggers) > 1 else [])
+ cohort = self._cohort(filters=filters(*leaves))
+ for kind, trigger in triggers.items():
+ get_redis_client().set(cohort_backfill_pending_key(cohort.id, kind), trigger, ex=300)
+
+ readiness = resolve_realtime_readiness([cohort])[cohort.id]
+ assert readiness.state == expected
+ assert readiness.build is not None
+ assert readiness.build.phase == CohortHistoryBuildPhase.WAITING
+ assert readiness.build.updated_at is None
+
+ def test_a_started_run_outranks_the_debounce_key(self) -> None:
+ cohort = self._cohort()
+ get_redis_client().set(
+ cohort_backfill_pending_key(cohort.id, CohortBackfillKind.BEHAVIORAL),
+ CohortBackfillTrigger.COHORT_CREATED,
+ ex=300,
+ )
+ self._participate(self._run(status=CohortBackfillRunStatus.RECONCILING, cohort=cohort), cohort)
+
+ build = resolve_realtime_readiness([cohort])[cohort.id].build
+ assert build is not None
+ assert build.phase == CohortHistoryBuildPhase.CHECKING
+
+ @parameterized.expand(
+ [
+ (CohortBackfillRunStatus.AWAITING_BOUNDARY, CohortHistoryBuildPhase.WAITING),
+ (CohortBackfillRunStatus.SEEDING, CohortHistoryBuildPhase.SCANNING),
+ (CohortBackfillRunStatus.RECONCILING, CohortHistoryBuildPhase.CHECKING),
+ ]
+ )
+ def test_active_run_reports_its_phase(self, run_status: str, phase: str) -> None:
+ cohort = self._cohort()
+ self._participate(self._run(status=run_status, cohort=cohort), cohort)
+
+ readiness = resolve_realtime_readiness([cohort])[cohort.id]
+ assert readiness.state == CohortRealtimeState.BUILDING
+ assert readiness.build is not None
+ assert readiness.build.phase == phase
+
+ @parameterized.expand(
+ [
+ (CohortBackfillRunStatus.BLOCKED,),
+ (CohortBackfillRunStatus.FAILED,),
+ (CohortBackfillRunStatus.CANCELLED,),
+ (CohortBackfillRunStatus.SUPERSEDED,),
+ ]
+ )
+ def test_run_that_is_not_making_progress_needs_attention(self, run_status: str) -> None:
+ cohort = self._cohort()
+ self._participate(self._run(status=run_status, cohort=cohort), cohort)
+
+ readiness = resolve_realtime_readiness([cohort])[cohort.id]
+ assert readiness.state == CohortRealtimeState.NEEDS_ATTENTION
+ assert readiness.build is None
+
+ def test_edit_triggered_run_rebuilds(self) -> None:
+ cohort = self._cohort()
+ self._participate(self._run(trigger=CohortBackfillTrigger.COHORT_EDITED, cohort=cohort), cohort)
+
+ assert self._state(cohort) == CohortRealtimeState.REBUILDING
+
+ def test_team_run_builds_the_cohorts_participating_in_it(self) -> None:
+ # A team enablement run carries no cohort_id, so reading runs instead of participations
+ # would leave every cohort it is building reading as needs_attention.
+ cohort = self._cohort()
+ self._participate(self._run(scope=CohortBackfillScope.TEAM), cohort)
+
+ assert self._state(cohort) == CohortRealtimeState.BUILDING
+
+ def test_a_superseded_participation_does_not_report_the_build_it_left(self) -> None:
+ # Editing a cohort a team run is building supersedes only its participation; the run keeps
+ # running for the rest of the team. Reading that row would show the abandoned build and
+ # hide the rebuild the edit just queued.
+ cohort = self._cohort()
+ participation = self._participate(self._run(scope=CohortBackfillScope.TEAM), cohort)
+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(id=participation.id).update(
+ superseded_at=timezone.now()
+ )
+ get_redis_client().set(
+ cohort_backfill_pending_key(cohort.id, CohortBackfillKind.BEHAVIORAL),
+ CohortBackfillTrigger.COHORT_EDITED,
+ ex=300,
+ )
+
+ assert self._state(cohort) == CohortRealtimeState.REBUILDING
+
+ def test_a_cohort_waiting_on_two_kinds_shows_the_one_furthest_behind(self) -> None:
+ # Both stamps gate flag targeting, so the cohort is only as far along as its slower build.
+ cohort = self._cohort(filters=filters(BEHAVIORAL_LEAF, PERSON_LEAF))
+ self._participate(self._run(status=CohortBackfillRunStatus.RECONCILING, cohort=cohort), cohort)
+ self._participate(
+ self._run(status=CohortBackfillRunStatus.SEEDING, kind=CohortBackfillKind.PERSON_PROPERTY, cohort=cohort),
+ cohort,
+ )
+
+ build = resolve_realtime_readiness([cohort])[cohort.id].build
+ assert build is not None
+ assert build.phase == CohortHistoryBuildPhase.SCANNING
+
+ def test_a_kind_parked_on_an_operator_stops_the_build_reading_as_in_progress(self) -> None:
+ # A blocked run needs a person, so a cohort waiting on one is not making progress however
+ # well its other kind is going.
+ cohort = self._cohort(filters=filters(BEHAVIORAL_LEAF, PERSON_LEAF))
+ self._participate(self._run(status=CohortBackfillRunStatus.SEEDING, cohort=cohort), cohort)
+ self._participate(
+ self._run(status=CohortBackfillRunStatus.BLOCKED, kind=CohortBackfillKind.PERSON_PROPERTY, cohort=cohort),
+ cohort,
+ )
+
+ assert self._state(cohort) == CohortRealtimeState.NEEDS_ATTENTION
+
+ def test_a_required_kind_with_nothing_building_it_is_not_hidden_by_the_other_one(self) -> None:
+ # Both kinds are triggered separately, so one can be refused or lost while the other runs.
+ # Reporting the running one as the cohort's progress would leave a bar climbing towards a
+ # ready state the missing kind is never going to allow.
+ cohort = self._cohort(filters=filters(BEHAVIORAL_LEAF, PERSON_LEAF))
+ self._participate(self._run(status=CohortBackfillRunStatus.SEEDING, cohort=cohort), cohort)
+
+ readiness = resolve_realtime_readiness([cohort])[cohort.id]
+ assert readiness.state == CohortRealtimeState.NEEDS_ATTENTION
+ assert readiness.build is None
+
+ get_redis_client().set(
+ cohort_backfill_pending_key(cohort.id, CohortBackfillKind.PERSON_PROPERTY),
+ CohortBackfillTrigger.COHORT_CREATED,
+ ex=300,
+ )
+ assert self._state(cohort) == CohortRealtimeState.BUILDING
+
+ def test_a_run_for_a_kind_the_filters_no_longer_need_decides_nothing(self) -> None:
+ # A person run left over from an earlier definition is not something this cohort waits on,
+ # so neither its progress nor its being blocked describes the cohort.
+ cohort = self._cohort()
+ self._participate(
+ self._run(status=CohortBackfillRunStatus.BLOCKED, kind=CohortBackfillKind.PERSON_PROPERTY, cohort=cohort),
+ cohort,
+ )
+ self._participate(self._run(status=CohortBackfillRunStatus.SEEDING, cohort=cohort), cohort)
+
+ readiness = resolve_realtime_readiness([cohort])[cohort.id]
+ assert readiness.state == CohortRealtimeState.BUILDING
+ assert readiness.build is not None
+ assert readiness.build.phase == CohortHistoryBuildPhase.SCANNING
+
+ def test_the_build_timestamp_follows_chunk_progress(self) -> None:
+ # Confirming a chunk never touches the run row, so reporting the run's own timestamp would
+ # leave the page claiming no progress for hours while the percentage climbed.
+ cohort = self._cohort()
+ run = self._run(cohort=cohort)
+ self._participate(run, cohort)
+ self._chunks(run, total=2, confirmed=1)
+
+ build = resolve_realtime_readiness([cohort])[cohort.id].build
+ assert build is not None
+ assert build.updated_at is not None
+ assert build.updated_at >= run.updated_at
+
+ def test_a_failed_debounce_lookup_reports_no_state_rather_than_a_wrong_one(self) -> None:
+ # Redis is the only record of a queued build, so a lookup that fails cannot tell a cohort
+ # nothing is preparing from one whose build task is waiting out its countdown.
+ cohort = self._cohort()
+ with patch("products.cohorts.backend.realtime_state.get_redis_client", side_effect=RuntimeError("down")):
+ assert resolve_realtime_readiness([cohort]) == {}
+
+ def test_scan_progress_comes_from_confirmed_chunks(self) -> None:
+ cohort = self._cohort()
+ run = self._run(cohort=cohort)
+ self._participate(run, cohort)
+ self._chunks(run, total=4, confirmed=1)
+
+ build = resolve_realtime_readiness([cohort])[cohort.id].build
+ assert build is not None
+ assert build.percent_complete == 25
+
+ def test_a_run_past_the_scan_reports_no_progress(self) -> None:
+ # Reconciling confirms every chunk, so reading the tally there would park the bar at 100%
+ # under "checking", which reads as a build that finished and then stalled.
+ cohort = self._cohort()
+ run = self._run(status=CohortBackfillRunStatus.RECONCILING, cohort=cohort)
+ self._participate(run, cohort)
+ self._chunks(run, total=4, confirmed=4)
+
+ build = resolve_realtime_readiness([cohort])[cohort.id].build
+ assert build is not None
+ assert build.phase == CohortHistoryBuildPhase.CHECKING
+ assert build.percent_complete is None
+
+ def test_scan_progress_rounds_down_so_100_means_finished(self) -> None:
+ cohort = self._cohort()
+ run = self._run(cohort=cohort)
+ self._participate(run, cohort)
+ self._chunks(run, total=200, confirmed=199)
+
+ build = resolve_realtime_readiness([cohort])[cohort.id].build
+ assert build is not None
+ assert build.percent_complete == 99
+
+ def test_run_with_no_chunks_yet_reports_no_progress(self) -> None:
+ cohort = self._cohort()
+ self._participate(self._run(cohort=cohort), cohort)
+
+ build = resolve_realtime_readiness([cohort])[cohort.id].build
+ assert build is not None
+ assert build.percent_complete is None
+
+ def test_newest_run_wins_when_a_cohort_has_several(self) -> None:
+ cohort = self._cohort()
+ now = timezone.now()
+ self._participate(
+ self._run(status=CohortBackfillRunStatus.FAILED, cohort=cohort, created_at=now - timedelta(hours=2)),
+ cohort,
+ )
+ self._participate(self._run(cohort=cohort, created_at=now), cohort)
+
+ assert self._state(cohort) == CohortRealtimeState.BUILDING
+
+ def test_stamped_cohort_is_ready_and_dates_from_the_stamp_its_filters_need(self) -> None:
+ # A behavioral-only cohort can carry a person stamp from an earlier definition. Dating
+ # readiness from the later of the two stamps would report a backfill this cohort never used.
+ events_stamp = timezone.now() - timedelta(hours=3)
+ cohort = self._cohort(last_backfill_events_at=events_stamp, last_backfill_person_properties_at=timezone.now())
+
+ readiness = resolve_realtime_readiness([cohort])[cohort.id]
+ assert readiness.state == CohortRealtimeState.READY
+ assert readiness.ready_at == events_stamp
+
+ def test_mixed_cohort_is_ready_once_both_stamps_land(self) -> None:
+ cohort = self._cohort(filters=filters(BEHAVIORAL_LEAF, PERSON_LEAF), last_backfill_events_at=timezone.now())
+ assert self._state(cohort) == CohortRealtimeState.NEEDS_ATTENTION
+
+ cohort.last_backfill_person_properties_at = timezone.now()
+ assert self._state(cohort) == CohortRealtimeState.READY
+
+ @parameterized.expand(
+ [
+ ("static", {"is_static": True, "cohort_type": CohortType.STATIC}, CohortRealtimeState.STATIC),
+ ("not_realtime", {"cohort_type": CohortType.BEHAVIORAL}, CohortRealtimeState.DAILY),
+ # Neither kind of criteria decides anything: the realtime evaluator has no leaf to key
+ # membership on, and the flag API does not gate on a cohort reference either.
+ ("cohort_reference_only", {"filters": filters(COHORT_LEAF)}, None),
+ ]
+ )
+ def test_cohorts_outside_the_realtime_path(self, _name: str, kwargs: dict, expected: str | None) -> None:
+ assert self._state(self._cohort(**kwargs)) == expected
+
+ def test_a_person_property_cohort_is_targetable_and_names_no_readiness_moment(self) -> None:
+ # Flags read person properties off the person as they evaluate, so this cohort is
+ # targetable whatever the pipeline did, and it must not read as unavailable. A stamp left
+ # by an earlier definition must not date a readiness this state does not claim.
+ cohort = self._cohort(filters=filters(PERSON_LEAF), last_backfill_person_properties_at=timezone.now())
+
+ readiness = resolve_realtime_readiness([cohort])[cohort.id]
+ assert readiness.state == CohortRealtimeState.PERSON_PROPERTIES
+ assert readiness.ready_at is None
+ assert readiness.build is None
+
+ def test_a_legacy_cohort_keeping_its_event_condition_in_groups_reads_as_daily(self) -> None:
+ # These carry no `filters` at all, so walking that alone leaves them with no state, which
+ # a list row reads as "feature flags can target this". Saving a flag against one fails.
+ cohort = self._cohort(filters={}, groups=[{"action_id": 3, "days": 7}], cohort_type=CohortType.BEHAVIORAL)
+
+ assert self._state(cohort) == CohortRealtimeState.DAILY
+
+ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="none")
+ def test_team_without_the_pipeline_has_no_realtime_state(self) -> None:
+ # Cohort type is computed for every team, so without this gate every cohort in the fleet
+ # would claim a realtime state the team's flags can never read.
+ cohort = self._cohort()
+ with self.assertNumQueries(0):
+ assert resolve_realtime_readiness([cohort]) == {}
+
+ def test_resolving_a_page_costs_the_same_queries_as_one_cohort(self) -> None:
+ # The cohort list and the flag picker's typeahead both resolve a whole page, so the cost
+ # has to be per page, not per row.
+ cohorts = []
+ for _ in range(5):
+ cohort = self._cohort()
+ self._participate(self._run(cohort=cohort), cohort)
+ cohorts.append(cohort)
+
+ # The shape right after a save: one cohort on the page is carried by the debounce key
+ # alone, so the branch that falls through to Redis runs inside the query budget too.
+ queued = self._cohort()
+ get_redis_client().set(
+ cohort_backfill_pending_key(queued.id, CohortBackfillKind.BEHAVIORAL),
+ CohortBackfillTrigger.COHORT_CREATED,
+ ex=300,
+ )
+ cohorts.append(queued)
+
+ with self.assertNumQueries(2):
+ readiness = resolve_realtime_readiness(cohorts)
+ assert len(readiness) == 6
+
+ def test_a_page_of_settled_cohorts_reads_no_backfill_rows(self) -> None:
+ # Stamped, static and daily cohorts are the steady state, so the common page costs nothing.
+ settled = [
+ self._cohort(last_backfill_events_at=timezone.now()),
+ self._cohort(is_static=True, cohort_type=CohortType.STATIC),
+ self._cohort(cohort_type=CohortType.BEHAVIORAL),
+ ]
+
+ with self.assertNumQueries(0):
+ assert len(resolve_realtime_readiness(settled)) == 3
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index 0e08eef9b2a5..642b4658483e 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -302,6 +302,80 @@ export interface CohortConditionTypeFlagsApi {
cohorts: boolean
}
+/**
+ * * `static` - Static
+ * * `person_properties` - Person properties
+ * * `daily` - Daily
+ * * `building` - Building
+ * * `rebuilding` - Rebuilding
+ * * `ready` - Ready
+ * * `needs_attention` - Needs attention
+ */
+export type CohortRealtimeStateEnumApi = (typeof CohortRealtimeStateEnumApi)[keyof typeof CohortRealtimeStateEnumApi]
+
+export const CohortRealtimeStateEnumApi = {
+ Static: 'static',
+ PersonProperties: 'person_properties',
+ Daily: 'daily',
+ Building: 'building',
+ Rebuilding: 'rebuilding',
+ Ready: 'ready',
+ NeedsAttention: 'needs_attention',
+} as const
+
+/**
+ * * `waiting` - Waiting
+ * * `scanning` - Scanning
+ * * `checking` - Checking
+ */
+export type CohortHistoryBuildPhaseEnumApi =
+ (typeof CohortHistoryBuildPhaseEnumApi)[keyof typeof CohortHistoryBuildPhaseEnumApi]
+
+export const CohortHistoryBuildPhaseEnumApi = {
+ Waiting: 'waiting',
+ Scanning: 'scanning',
+ Checking: 'checking',
+} as const
+
+export interface CohortHistoryBuildApi {
+ /** What the build is doing now: `waiting` to start, `scanning` past events, or `checking` the membership it produced. A build that is queued but has not started reports `waiting` too.
+ *
+ * * `waiting` - Waiting
+ * * `scanning` - Scanning
+ * * `checking` - Checking */
+ phase: CohortHistoryBuildPhaseEnumApi
+ /**
+ * How much of the event history has been scanned, 0 to 100. Null outside the `scanning` phase, and while the scan is still being planned.
+ * @nullable
+ */
+ percent_complete: number | null
+ /**
+ * When this build last made progress. Null while it is still queued.
+ * @nullable
+ */
+ updated_at: string | null
+}
+
+export interface CohortRealtimeReadinessApi {
+ /** Whether feature flags can target this cohort now. `ready`: they can, and they see membership changes within about a minute. `building` / `rebuilding`: PostHog is preparing the cohort from past events, and flags cannot target it yet. `needs_attention`: the cohort qualifies but nothing is preparing it. `daily`: its criteria are not supported in realtime, so its membership only comes from the once-a-day calculation. `person_properties`: it matches on person properties, which flags read directly, so they can always target it. `static`: it is a fixed list of people.
+ *
+ * * `static` - Static
+ * * `person_properties` - Person properties
+ * * `daily` - Daily
+ * * `building` - Building
+ * * `rebuilding` - Rebuilding
+ * * `ready` - Ready
+ * * `needs_attention` - Needs attention */
+ state: CohortRealtimeStateEnumApi
+ /**
+ * When the cohort became targetable by feature flags. Null unless the state is `ready`.
+ * @nullable
+ */
+ ready_at: string | null
+ /** The build preparing the cohort. Null unless the state is `building` or `rebuilding`. */
+ build: CohortHistoryBuildApi | null
+}
+
export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]
export const SearchMatchTypeEnumApi = {
@@ -360,6 +434,8 @@ export interface CohortApi {
cohort_type?: CohortTypeEnumApi | BlankEnumApi | null
/** Flags describing which kinds of conditions the cohort's filters contain. Null when the cohort has no filters to classify. */
readonly condition_type: CohortConditionTypeFlagsApi | null
+ /** Whether feature flags can target this cohort, and the progress of the build that gets it there. Null outside the realtime cohort flag targeting rollout, on projects the realtime pipeline does not cover, and for cohorts that match on neither events nor person properties, which nothing in the flag API decides on. */
+ readonly realtime: CohortRealtimeReadinessApi | null
readonly experiment_set: readonly number[]
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type: SearchMatchTypeEnumApi | null
@@ -427,6 +503,8 @@ export interface PatchedCohortApi {
cohort_type?: CohortTypeEnumApi | BlankEnumApi | null
/** Flags describing which kinds of conditions the cohort's filters contain. Null when the cohort has no filters to classify. */
readonly condition_type?: CohortConditionTypeFlagsApi | null
+ /** Whether feature flags can target this cohort, and the progress of the build that gets it there. Null outside the realtime cohort flag targeting rollout, on projects the realtime pipeline does not cover, and for cohorts that match on neither events nor person properties, which nothing in the flag API decides on. */
+ readonly realtime?: CohortRealtimeReadinessApi | null
readonly experiment_set?: readonly number[]
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type?: SearchMatchTypeEnumApi | null
diff --git a/products/cohorts/frontend/realtime/CohortRealtimeStatus.tsx b/products/cohorts/frontend/realtime/CohortRealtimeStatus.tsx
new file mode 100644
index 000000000000..e1fd6bab91b9
--- /dev/null
+++ b/products/cohorts/frontend/realtime/CohortRealtimeStatus.tsx
@@ -0,0 +1,153 @@
+import { IconBolt, IconInfo } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
+
+import { CohortHistoryBuildPhaseEnumApi, CohortRealtimeReadinessApi } from '../generated/api.schemas'
+
+// Partial, so the fallback below stays reachable for a phase this bundle predates.
+const PHASE_DETAIL: Partial<Record<CohortHistoryBuildPhaseEnumApi, string>> = {
+ waiting: 'Waiting to start',
+ scanning: 'Reading past events',
+ checking: 'Checking who matches',
+}
+
+type RowContent = { label: JSX.Element; tooltip: JSX.Element }
+
+/** The label shown beside "Flag targeting:", and the sentence its ⓘ carries. */
+function rowContent(realtime: CohortRealtimeReadinessApi): RowContent | null {
+ switch (realtime.state) {
+ case 'ready':
+ return {
+ label: (
+ <span className="flex items-center gap-x-1">
+ <IconBolt className="text-base" />
+ Available
+ </span>
+ ),
+ tooltip: (
+ <div className="space-y-1">
+ <div>
+ This is a realtime cohort. Feature flags can target it and see membership changes within
+ about a minute. The member count and the people listed on this page still update once a day.
+ </div>
+ {realtime.ready_at && (
+ <div>
+ Ready since <TZLabel time={realtime.ready_at} />
+ </div>
+ )}
+ </div>
+ ),
+ }
+ case 'building':
+ case 'rebuilding':
+ return {
+ label: (
+ <span className="flex items-center gap-x-2 flex-wrap">
+ <span className="flex items-center gap-x-2">
+ <Spinner size="small" />
+ Preparing
+ </span>
+ {realtime.build && (
+ <span className="text-secondary flex gap-x-1">
+ <span>{PHASE_DETAIL[realtime.build.phase] ?? 'In progress'}</span>
+ {realtime.build.updated_at && (
+ <>
+ <span>·</span>
+ <span>Updated</span>
+ <TZLabel time={realtime.build.updated_at} />
+ </>
+ )}
+ </span>
+ )}
+ </span>
+ ),
+ tooltip: (
+ <div>
+ {realtime.state === 'rebuilding'
+ ? 'The criteria changed, so PostHog is rebuilding this cohort from past events before feature flags can target it again. This usually takes under 30 minutes.'
+ : 'PostHog is catching up on past events so feature flags can target this cohort. This usually takes under 30 minutes.'}
+ </div>
+ ),
+ }
+ case 'needs_attention':
+ return {
+ label: <span className="text-secondary">Unavailable</span>,
+ tooltip: (
+ <div>
+ Feature flags can't target this cohort yet because PostHog hasn't prepared it. Contact support
+ if this doesn't change.
+ </div>
+ ),
+ }
+ case 'daily':
+ return {
+ label: <span className="text-secondary">Unavailable</span>,
+ tooltip: (
+ <div>
+ Feature flags can't target this cohort. Its criteria are matched in the once-a-day calculation,
+ which feature flags can't read.
+ </div>
+ ),
+ }
+ case 'person_properties':
+ return {
+ label: <span>Available</span>,
+ tooltip: (
+ <div>
+ Feature flags can target this cohort. They read its person properties as they evaluate, so
+ membership is always current. The member count and the people listed on this page still update
+ once a day.
+ </div>
+ ),
+ }
+ default:
+ // Static cohorts, and any state this bundle predates: nothing to say.
+ return null
+ }
+}
+
+/**
+ * What feature flags can do with this cohort right now, as a row beside the cohort's other facts.
+ * Deliberately one row and not a banner: the daily calculation already has a banner on this page,
+ * and two progress stories stacked on a save read as one thing failing twice.
+ */
+export function CohortRealtimeStatus({
+ realtime,
+}: {
+ realtime: CohortRealtimeReadinessApi | null | undefined
+}): JSX.Element | null {
+ const realtimeTargetingEnabled = useFeatureFlag('REALTIME_COHORT_FLAG_TARGETING')
+ const content = realtime ? rowContent(realtime) : null
+ if (!realtimeTargetingEnabled || !content) {
+ return null
+ }
+
+ const percent = realtime?.build?.percent_complete ?? null
+
+ return (
+ <div className="flex flex-col gap-y-2" data-attr="cohort-realtime-status">
+ <div className="flex items-center gap-x-2 my-0 flex-wrap">
+ <strong>Flag targeting:</strong>
+ <Tooltip title={content.tooltip}>
+ <IconInfo className="text-secondary text-base" />
+ </Tooltip>
+ {content.label}
+ </div>
+ {percent !== null && (
+ <LemonProgress
+ percent={percent}
+ className="max-w-80"
+ role="progressbar"
+ aria-label="Cohort preparation progress"
+ aria-valuenow={percent}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/cohorts/frontend/realtime/CohortRealtimeTag.tsx b/products/cohorts/frontend/realtime/CohortRealtimeTag.tsx
new file mode 100644
index 000000000000..5df04a37f909
--- /dev/null
+++ b/products/cohorts/frontend/realtime/CohortRealtimeTag.tsx
@@ -0,0 +1,68 @@
+import { IconBolt } from '@posthog/icons'
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
+
+import { CohortRealtimeReadinessApi, CohortRealtimeStateEnumApi } from '../generated/api.schemas'
+
+type TagContent = { label: string; icon?: JSX.Element; explanation: string }
+
+// A tag appears on every cohort feature flags cannot target, and on the realtime ones they can, so
+// a bare row means one thing: flags can target this cohort. Every realtime label leads with the
+// word, so a row is never read as the daily calculation being unfinished (a bare "Preparing" beside
+// a finished calculation reads as the whole cohort not being ready). Only the ready state keeps the
+// bolt, which stands for flags seeing changes at once. `static` and `person_properties` get no tag:
+// flags can target both and neither has anything else to say. The cohort page carries the state in
+// full, including for those two.
+const TAG_BY_STATE: Partial<Record<CohortRealtimeStateEnumApi, TagContent>> = {
+ ready: {
+ label: 'Realtime',
+ icon: <IconBolt />,
+ explanation:
+ 'A realtime cohort. Feature flags can target it and see membership changes within about a minute. Insights and the member count still update once a day.',
+ },
+ building: {
+ label: 'Realtime · preparing',
+ icon: <Spinner textColored />,
+ explanation:
+ "A realtime cohort. PostHog is still preparing it, so feature flags can't target it yet. Open the cohort to see the progress.",
+ },
+ rebuilding: {
+ label: 'Realtime · preparing',
+ icon: <Spinner textColored />,
+ explanation:
+ "A realtime cohort. The criteria changed, so PostHog is preparing it again and feature flags can't target it until that finishes. Open the cohort to see the progress.",
+ },
+ needs_attention: {
+ label: 'Realtime · unavailable',
+ explanation: "A realtime cohort that feature flags can't target yet. Open the cohort for details.",
+ },
+ daily: {
+ label: 'No flag targeting',
+ explanation:
+ "Feature flags can't target this cohort. Its criteria are matched in the once-a-day calculation, which feature flags can't read.",
+ },
+}
+
+/** What feature flags can do with a cohort, for list and picker rows where a sentence is too much. */
+export function CohortRealtimeTag({
+ realtime,
+}: {
+ realtime: CohortRealtimeReadinessApi | null | undefined
+}): JSX.Element | null {
+ const realtimeTargetingEnabled = useFeatureFlag('REALTIME_COHORT_FLAG_TARGETING')
+ // A state this bundle predates reads as unknown, not as a state it happens to resemble.
+ const content = realtime ? TAG_BY_STATE[realtime.state] : undefined
+ if (!realtimeTargetingEnabled || !content) {
+ return null
+ }
+
+ return (
+ <Tooltip title={content.explanation}>
+ <LemonTag type="muted" size="small" icon={content.icon} data-attr="cohort-realtime-tag">
+ {content.label}
+ </LemonTag>
+ </Tooltip>
+ )
+}
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 8f20a2170620..a49ccbcd591e 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -122,6 +122,7 @@ from products.feature_flags.backend.flag_status import (
from products.feature_flags.backend.models.evaluation_context import normalize_context_name
from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboards
from products.feature_flags.backend.models.team_feature_flag_policy_config import team_requires_flag_tags
+from products.feature_flags.backend.realtime_targeting import is_realtime_cohort_flag_targeting_enabled
from products.feature_flags.backend.session_recording_links import (
REPLAY_GATE_DELETE_ERROR,
ReplayFlagGates,
@@ -235,7 +236,6 @@ def _count_filters_write_success(serializer: serializers.Serializer, operation:
BEHAVIOURAL_COHORT_FOUND_ERROR_CODE = "behavioral_cohort_found"
-REALTIME_COHORT_FLAG_TARGETING_FLAG = "realtime-cohort-flag-targeting"
EARLY_EXIT_FLAG = "feature-flag-early-exit"
# Gates enforcement of `feature_flag:write` on cross-resource flag mutations
@@ -393,25 +393,6 @@ def assert_feature_flag_write_scope(
)
-def _is_realtime_cohort_flag_targeting_enabled(request, *, team: Team) -> bool:
- """Check whether the realtime cohort flag targeting feature is enabled for this request."""
- try:
- user = getattr(request, "user", None)
- if user is None or user.is_anonymous:
- return False
- organization_id = str(team.organization_id)
- return feature_enabled_or_false(
- REALTIME_COHORT_FLAG_TARGETING_FLAG,
- user.distinct_id,
- groups={"organization": organization_id, "project": str(team.uuid)},
- group_properties={"organization": {"id": organization_id}, "project": {"id": team.id}},
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- except Exception:
- return False
-
-
def _describe_behavioral_properties(behavioral_props: list[Property]) -> str | None:
"""Human-readable summary of which condition(s) on a cohort are behavioral, so a
validation error can point at the specific thing to fix instead of a bare cohort name.
@@ -454,7 +435,7 @@ def _validate_behavioral_cohort_for_feature_flag(
code=BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,
)
raise serializers.ValidationError(
- detail=f"Cohort '{cohort.name}' is still being backfilled and cannot be used in feature flags yet. It will become available once its initial backfill completes.",
+ detail=f"Cohort '{cohort.name}' isn't ready for feature flags yet. Open the cohort to see whether PostHog is still preparing it, and try again once it shows as realtime.",
code=BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,
)
@@ -1591,7 +1572,7 @@ class FeatureFlagSerializer(
"""
get_team = self.context.get("get_team")
team = get_team() if get_team else Team.objects.get(pk=self.context["team_id"])
- return _is_realtime_cohort_flag_targeting_enabled(self.context["request"], team=team)
+ return is_realtime_cohort_flag_targeting_enabled(self.context["request"], team=team)
def validate_filters(self, filters):
# Metrics wrapper: one increment per rejected write. `rejected` means a switch-gated
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index c01889ee0c73..c9ae748726d5 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -62,7 +62,6 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.api.feature_flag import (
FLAG_FILTERS_VIOLATION_COUNTER,
FLAG_FILTERS_WRITE_COUNTER,
- REALTIME_COHORT_FLAG_TARGETING_FLAG,
FeatureFlagSerializer,
FeatureFlagStatusResponseSerializer,
_flag_write_source,
@@ -76,6 +75,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (
from products.feature_flags.backend.flag_status import FeatureFlagStatus
from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboards
from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig
+from products.feature_flags.backend.realtime_targeting import REALTIME_COHORT_FLAG_TARGETING_FLAG
from products.feature_flags.backend.test.replay_gate_fixtures import set_linked_flag, set_trigger_groups, trigger_groups
from products.feature_flags.backend.user_blast_radius import get_user_blast_radius, get_user_blast_radius_persons
from products.product_analytics.backend.facade.models import Insight
@@ -6311,7 +6311,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
False,
True,
status.HTTP_400_BAD_REQUEST,
- "is still being backfilled",
+ "isn't ready for feature flags yet",
),
(
"non_realtime_flag_on",
@@ -6331,6 +6331,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
),
]
)
+ @patch("products.feature_flags.backend.realtime_targeting.feature_enabled_or_false")
@patch("products.feature_flags.backend.api.feature_flag.feature_enabled_or_false")
def test_behavioral_cohort_flag_validation(
self,
@@ -6341,6 +6342,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
expected_status,
expected_detail_fragment,
mock_feature_enabled,
+ mock_realtime_gate,
):
def gate_enabled_for_request_project(key, _distinct_id, *, groups, group_properties, **_kwargs):
if key != REALTIME_COHORT_FLAG_TARGETING_FLAG:
@@ -6352,6 +6354,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
mock_feature_enabled.side_effect = gate_enabled_for_request_project
+ mock_realtime_gate.side_effect = gate_enabled_for_request_project
cohort_kwargs: dict[str, Any] = {
"team": self.team,
diff --git a/products/feature_flags/backend/realtime_targeting.py b/products/feature_flags/backend/realtime_targeting.py
new file mode 100644
index 000000000000..c0b765b82f0f
--- /dev/null
+++ b/products/feature_flags/backend/realtime_targeting.py
@@ -0,0 +1,36 @@
+"""The rollout gate for targeting realtime cohorts from feature flags.
+
+Its own module because both API modules read it and they import each other: the feature flag API
+imports `CohortSerializer` from `posthog.api.cohort`, so the cohort API cannot import the flag API
+back at module level. A module neither of them imports lets both reach the gate normally.
+"""
+
+from typing import Any
+
+from posthog.models.team import Team
+from posthog.ph_client import feature_enabled_or_false
+
+REALTIME_COHORT_FLAG_TARGETING_FLAG = "realtime-cohort-flag-targeting"
+
+
+def is_realtime_cohort_flag_targeting_enabled(request: Any, *, team: Team) -> bool:
+ """Whether this request's user is in the realtime cohort flag targeting rollout.
+
+ Cloud evaluates the flag locally in the common case, but this is allowed to fall back to a
+ remote call, so callers ask only about cohorts the answer could change something for.
+ """
+ try:
+ user = getattr(request, "user", None)
+ if user is None or user.is_anonymous:
+ return False
+ organization_id = str(team.organization_id)
+ return feature_enabled_or_false(
+ REALTIME_COHORT_FLAG_TARGETING_FLAG,
+ user.distinct_id,
+ groups={"organization": organization_id, "project": str(team.uuid)},
+ group_properties={"organization": {"id": organization_id}, "project": {"id": team.id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ return False
diff --git a/products/feature_flags/frontend/CohortConditionLink.tsx b/products/feature_flags/frontend/CohortConditionLink.tsx
new file mode 100644
index 000000000000..66b3d108aa9f
--- /dev/null
+++ b/products/feature_flags/frontend/CohortConditionLink.tsx
@@ -0,0 +1,33 @@
+import { useValues } from 'kea'
+
+import { IconBolt } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { IconOpenInNew } from 'lib/lemon-ui/icons'
+import { urls } from 'scenes/urls'
+
+import { cohortsModel } from '~/models/cohortsModel'
+import { CohortPropertyFilter } from '~/types'
+
+/** The cohort a flag condition targets, linked, with a bolt when flags read its membership in realtime. */
+export function CohortConditionLink({ property }: { property: CohortPropertyFilter }): JSX.Element {
+ const { cohortsById } = useValues(cohortsModel)
+ const realtimeTargetingEnabled = useFeatureFlag('REALTIME_COHORT_FLAG_TARGETING')
+ const isRealtime = realtimeTargetingEnabled && cohortsById[property.value]?.realtime?.state === 'ready'
+
+ return (
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ to={urls.cohort(property.value)}
+ icon={isRealtime ? <IconBolt /> : undefined}
+ tooltip={
+ isRealtime ? 'Realtime cohort. Feature flags see membership changes within about a minute.' : undefined
+ }
+ sideIcon={<IconOpenInNew />}
+ >
+ {property.cohort_name || `ID ${property.value}`}
+ </LemonButton>
+ )
+}
diff --git a/products/feature_flags/frontend/FeatureFlagConditionSetCard.tsx b/products/feature_flags/frontend/FeatureFlagConditionSetCard.tsx
index 69940860ad8d..ddd9ee7680b0 100644
--- a/products/feature_flags/frontend/FeatureFlagConditionSetCard.tsx
+++ b/products/feature_flags/frontend/FeatureFlagConditionSetCard.tsx
@@ -4,13 +4,13 @@ import { LemonButton, LemonSnack, LemonTag } from '@posthog/lemon-ui'
import { allOperatorsToHumanName } from 'lib/components/DefinitionPopover/utils'
import { isPropertyFilterWithOperator } from 'lib/components/PropertyFilters/utils'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { IconOpenInNew, IconSubArrowRight } from 'lib/lemon-ui/icons'
+import { IconSubArrowRight } from 'lib/lemon-ui/icons'
import { isDistinctIdFilter, withResolvedFlagLabels } from 'scenes/feature-flags/featureFlagReleaseConditionsLogic'
-import { urls } from 'scenes/urls'
import { getFilterLabel } from '~/taxonomy/helpers'
import { AnyPropertyFilter, FeatureFlagGroupType, PropertyFilterType } from '~/types'
+import { CohortConditionLink } from './CohortConditionLink'
import { rolloutOf } from './releaseConditionsDiff'
export interface FeatureFlagConditionSetCardProps {
@@ -41,11 +41,7 @@ function PropertyValueDisplay({
getDistinctIdName: (distinctId: string) => string
}): JSX.Element {
if (property.type === PropertyFilterType.Cohort) {
- return (
- <LemonButton type="secondary" size="xsmall" to={urls.cohort(property.value)} sideIcon={<IconOpenInNew />}>
- {property.cohort_name || `ID ${property.value}`}
- </LemonButton>
- )
+ return <CohortConditionLink property={property} />
}
const propertyValues = Array.isArray(property.value) ? property.value : [property.value]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 29d65ef06703..0395967d8b48 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19516,6 +19516,81 @@ export namespace Schemas {
cohorts: boolean;
}
+ /**
+ * * `static` - Static
+ * * `person_properties` - Person properties
+ * * `daily` - Daily
+ * * `building` - Building
+ * * `rebuilding` - Rebuilding
+ * * `ready` - Ready
+ * * `needs_attention` - Needs attention
+ */
+ export type CohortRealtimeStateEnum = typeof CohortRealtimeStateEnum[keyof typeof CohortRealtimeStateEnum];
+
+
+ export const CohortRealtimeStateEnum = {
+ Static: 'static',
+ PersonProperties: 'person_properties',
+ Daily: 'daily',
+ Building: 'building',
+ Rebuilding: 'rebuilding',
+ Ready: 'ready',
+ NeedsAttention: 'needs_attention',
+ } as const;
+
+ /**
+ * * `waiting` - Waiting
+ * * `scanning` - Scanning
+ * * `checking` - Checking
+ */
+ export type CohortHistoryBuildPhaseEnum = typeof CohortHistoryBuildPhaseEnum[keyof typeof CohortHistoryBuildPhaseEnum];
+
+
+ export const CohortHistoryBuildPhaseEnum = {
+ Waiting: 'waiting',
+ Scanning: 'scanning',
+ Checking: 'checking',
+ } as const;
+
+ export interface CohortHistoryBuild {
+ /** What the build is doing now: `waiting` to start, `scanning` past events, or `checking` the membership it produced. A build that is queued but has not started reports `waiting` too.
+ *
+ * * `waiting` - Waiting
+ * * `scanning` - Scanning
+ * * `checking` - Checking */
+ phase: CohortHistoryBuildPhaseEnum;
+ /**
+ * How much of the event history has been scanned, 0 to 100. Null outside the `scanning` phase, and while the scan is still being planned.
+ * @nullable
+ */
+ percent_complete: number | null;
+ /**
+ * When this build last made progress. Null while it is still queued.
+ * @nullable
+ */
+ updated_at: string | null;
+ }
+
+ export interface CohortRealtimeReadiness {
+ /** Whether feature flags can target this cohort now. `ready`: they can, and they see membership changes within about a minute. `building` / `rebuilding`: PostHog is preparing the cohort from past events, and flags cannot target it yet. `needs_attention`: the cohort qualifies but nothing is preparing it. `daily`: its criteria are not supported in realtime, so its membership only comes from the once-a-day calculation. `person_properties`: it matches on person properties, which flags read directly, so they can always target it. `static`: it is a fixed list of people.
+ *
+ * * `static` - Static
+ * * `person_properties` - Person properties
+ * * `daily` - Daily
+ * * `building` - Building
+ * * `rebuilding` - Rebuilding
+ * * `ready` - Ready
+ * * `needs_attention` - Needs attention */
+ state: CohortRealtimeStateEnum;
+ /**
+ * When the cohort became targetable by feature flags. Null unless the state is `ready`.
+ * @nullable
+ */
+ ready_at: string | null;
+ /** The build preparing the cohort. Null unless the state is `building` or `rebuilding`. */
+ build: CohortHistoryBuild | null;
+ }
+
export interface Cohort {
readonly id: number;
/**
@@ -19567,6 +19642,8 @@ export namespace Schemas {
cohort_type?: CohortTypeEnum | BlankEnum | null;
/** Flags describing which kinds of conditions the cohort's filters contain. Null when the cohort has no filters to classify. */
readonly condition_type: CohortConditionTypeFlags | null;
+ /** Whether feature flags can target this cohort, and the progress of the build that gets it there. Null outside the realtime cohort flag targeting rollout, on projects the realtime pipeline does not cover, and for cohorts that match on neither events nor person properties, which nothing in the flag API decides on. */
+ readonly realtime: CohortRealtimeReadiness | null;
readonly experiment_set: readonly number[];
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type: SearchMatchTypeEnum | null;
@@ -65833,6 +65910,8 @@ export namespace Schemas {
cohort_type?: CohortTypeEnum | BlankEnum | null;
/** Flags describing which kinds of conditions the cohort's filters contain. Null when the cohort has no filters to classify. */
readonly condition_type?: CohortConditionTypeFlags | null;
+ /** Whether feature flags can target this cohort, and the progress of the build that gets it there. Null outside the realtime cohort flag targeting rollout, on projects the realtime pipeline does not cover, and for cohorts that match on neither events nor person properties, which nothing in the flag API decides on. */
+ readonly realtime?: CohortRealtimeReadiness | null;
readonly experiment_set?: readonly number[];
/** How this row matched the `search` query parameter: `exact` (the term is a case-insensitive substring of a searched field) or `similar` (a fuzzy trigram match, returned only when no exact match exists). Null when the list is not filtered by `search`. */
readonly search_match_type?: SearchMatchTypeEnum | null;