:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): add relative date track rules (#90649)
Arthur Moreira de Deus48555d8b17b8
diff --git a/frontend/src/lib/components/DateFilter/DateFilter.test.tsx b/frontend/src/lib/components/DateFilter/DateFilter.test.tsxindex 8611b9acd7c7..09574e069964 100644--- a/frontend/src/lib/components/DateFilter/DateFilter.test.tsx+++ b/frontend/src/lib/components/DateFilter/DateFilter.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { cleanup, render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { Provider } from 'kea'@@ -12,14 +12,15 @@ import { DateFilter } from './DateFilter'describe('DateFilter', () => {let onChange = jest.fn()+ let rerender: ReturnType<typeof render>['rerender']beforeEach(() => {initKeaTests()onChange = jest.fn()- render(+ rerender = render(<Provider><DateFilter onChange={onChange} dateOptions={dateMapping} /></Provider>- )+ ).rerender})afterEach(() => {@@ -36,6 +37,28 @@ describe('DateFilter', () => {expect(onChange).toHaveBeenCalledWith('-1dStart', '-1dEnd', false)})+ it('can set a future relative date', async () => {+ rerender(+ <Provider>+ <DateFilter+ onChange={onChange}+ dateOptions={dateMapping}+ isFixedDateMode+ allowFutureRelativeDateOptions+ />+ </Provider>+ )+ await userEvent.click(screen.getByTestId('date-filter'))++ const futureFilter = screen.getByTestId('future-rolling-date-range-filter')+ const futureInput = within(futureFilter).getByTestId('rolling-date-range-input')+ await userEvent.clear(futureInput)+ await userEvent.type(futureInput, '10')+ await userEvent.click(futureFilter)++ await waitFor(() => expect(onChange).toHaveBeenCalledWith('+10d', null, false))+ })+it('can set a custom rolling date range', async () => {const dateFilter = screen.getByTestId('date-filter')await userEvent.click(dateFilter)diff --git a/frontend/src/lib/components/DateFilter/DateFilter.tsx b/frontend/src/lib/components/DateFilter/DateFilter.tsxindex e3e90cd32033..c23657fad517 100644--- a/frontend/src/lib/components/DateFilter/DateFilter.tsx+++ b/frontend/src/lib/components/DateFilter/DateFilter.tsx@@ -57,6 +57,7 @@ export interface DateFilterProps {resolvedDateRange?: ResolvedDateRangeResponseshowJumpToTimestamp?: booleanshowCustomRelativeRange?: boolean+ allowFutureRelativeDateOptions?: booleanfooterComponent?: (onClose: () => void) => React.ReactNode/*** When true, surfaces every option — presets, rolling picker, "Custom date…" (single exact),@@ -128,6 +129,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(funcresolvedDateRange,showJumpToTimestamp = false,showCustomRelativeRange = false,+ allowFutureRelativeDateOptions = false,allowSingleAndRange = false,onOpenChange,footerComponent,@@ -197,10 +199,12 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(funcconst { weekStartDay } = useValues(teamLogic)const optionsRef = useRef<HTMLDivElement | null>(null)const rollingDateRangeRef = useRef<HTMLDivElement | null>(null)+ const futureRollingDateRangeRef = useRef<HTMLDivElement | null>(null)const [granularity, setGranularity] = useState<LemonCalendarSelectProps['granularity']>(forceGranularity ?? (dateFromHasTimePrecision ? 'minute' : 'day'))+ const isFutureRelativeDate = typeof dateFrom === 'string' && /^\+?\d+[hdwmqyMs]$/.test(dateFrom)const showFixedRangeTimeToggle = allowTimePrecision || allowFixedRangeWithTimeconst showExclusions =(showIncompletePeriodExclusion || showDaysOfWeekExclusions) && !!exclusions && !!onExclusionsChange@@ -355,7 +359,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(funcsize={optionsSize}dateFrom={dateFrom}dateRangeFilterLabel={isFixedDateMode ? 'Last' : undefined}- selected={isRollingDateRange}+ selected={isRollingDateRange && !isFutureRelativeDate}onChange={(fromDate) => {setDate(fromDate, '', true, explicitDate)}}@@ -372,6 +376,30 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(funcfullWidth/>)}+ {allowFutureRelativeDateOptions && (+ <RollingDateRangeFilter+ pageKey={`${key}-future`}+ size={optionsSize}+ dateFrom={dateFrom}+ dateRangeFilterLabel="In the next"+ direction="future"+ selected={isRollingDateRange && isFutureRelativeDate}+ onChange={(fromDate) => {+ setDate(fromDate, '', true, explicitDate)+ }}+ makeLabel={makeLabel}+ popover={{+ ref: futureRollingDateRangeRef,+ }}+ max={max}+ allowedDateOptions={+ isFixedDateMode && !allowedRollingDateOptions+ ? ['hours', 'days', 'weeks', 'months', 'years']+ : allowedRollingDateOptions+ }+ fullWidth+ />+ )}</ScrollableShadows>{showFooter && (<div className="shrink-0 deprecated-space-y-px p-1">@@ -481,7 +509,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(funcoverlay={popoverOverlay}placement={dropdownPlacement}actionable- additionalRefs={[rollingDateRangeRef]}+ additionalRefs={[rollingDateRangeRef, futureRollingDateRangeRef]}onClickOutside={close}closeParentPopoverOnClickInside={false}overflowHidden={view === DateFilterView.QuickList}diff --git a/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx b/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsxindex a40548c6afdb..981f4cbd4b35 100644--- a/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx+++ b/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx@@ -7,7 +7,7 @@ import { LemonButton, LemonButtonProps, LemonInput, LemonSelect, LemonSelectOptiimport { dayjs } from 'lib/dayjs'import { Tooltip } from 'lib/lemon-ui/Tooltip'-import { DateOption, rollingDateRangeFilterLogic } from './rollingDateRangeFilterLogic'+import { type DateOption, type RelativeDateDirection, rollingDateRangeFilterLogic } from './rollingDateRangeFilterLogic'const dateOptions: LemonSelectOptionLeaf<DateOption>[] = [{ value: 'seconds', label: 'seconds' },@@ -36,6 +36,7 @@ type RollingDateRangeFilterProps = {}dateRangeFilterLabel?: stringdateRangeFilterSuffixLabel?: string+ direction?: RelativeDateDirectionallowedDateOptions?: DateOption[]fullWidth?: LemonButtonProps['fullWidth']size?: 'small' | 'medium'@@ -52,12 +53,13 @@ export function RollingDateRangeFilter({max,dateRangeFilterLabel = 'In the last',dateRangeFilterSuffixLabel,+ direction = 'past',pageKey,allowedDateOptions = ['days', 'weeks', 'months', 'years'],fullWidth,size,}: RollingDateRangeFilterProps): JSX.Element {- const logicProps = { onChange, dateFrom, inUse: selected || inUse, max, pageKey }+ const logicProps = { onChange, dateFrom, inUse: selected || inUse, max, pageKey, direction }const { increaseCounter, decreaseCounter, setCounter, setDateOption, toggleDateOptionsSelector, select } =useActions(rollingDateRangeFilterLogic(logicProps))const { counter, dateOption, formattedDate, startOfDateRange } = useValues(rollingDateRangeFilterLogic(logicProps))@@ -117,7 +119,8 @@ export function RollingDateRangeFilter({contents = (<LemonButtonclassName="RollingDateRangeFilter"- data-attr="rolling-date-range-filter"+ // Pinned: changing this breaks autocapture dashboards and UI tests.+ data-attr={direction === 'future' ? 'future-rolling-date-range-filter' : 'rolling-date-range-filter'}onClick={select}active={selected}size={size}diff --git a/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.test.ts b/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.test.tsindex 861274103fa9..7bd97c35e7a8 100644--- a/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.test.ts+++ b/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.test.ts@@ -42,6 +42,17 @@ describe('rollingDateRangeFilterLogic', () => {})})+ it('sets a future relative date when configured', () => {+ logic = rollingDateRangeFilterLogic({ direction: 'future' })+ logic.mount()+ expectLogic(logic, () => {+ logic.actions.setCounter(10)+ logic.actions.setDateOption('days')+ }).toMatchValues({+ value: '+10d',+ })+ })+it('cannot set the date higher than the max', () => {logic = rollingDateRangeFilterLogic({ max: 6 })logic.mount()diff --git a/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.ts b/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.tsindex 9d7d07872217..bb41746267e4 100644--- a/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.ts+++ b/frontend/src/lib/components/DateFilter/rollingDateRangeFilterLogic.ts@@ -17,8 +17,10 @@ const dateOptionsMap = {} as constexport type DateOption = (typeof dateOptionsMap)[keyof typeof dateOptionsMap]+export type RelativeDateDirection = 'past' | 'future'export type RollingDateFilterLogicPropsType = {+ direction?: RelativeDateDirectioninUse?: booleanonChange?: (fromDate: string) => voiddateFrom?: Dayjs | string | null@@ -82,7 +84,7 @@ export interface rollingDateRangeFilterLogicActions {export interface rollingDateRangeFilterLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {- value: (counter: number | null, dateOption: DateOption) => string+ value: (counter: number | null, dateOption: DateOption, arg: any) => stringformattedDate: (value: string) => string | nullstartOfDateRange: (value: string) => string | null}@@ -143,30 +145,31 @@ export const rollingDateRangeFilterLogic = kea<rollingDateRangeFilterLogicType>(})),selectors(() => ({value: [- (s) => [s.counter, s.dateOption],- (counter: number | null, dateOption: DateOption) => {+ (s) => [s.counter, s.dateOption, (_, props) => props.direction ?? 'past'],+ (counter: number | null, dateOption: DateOption, direction: RelativeDateDirection) => {if (!counter) {return ''}+ const sign = direction === 'future' ? '+' : '-'switch (dateOption) {case 'years':- return `-${counter}y`+ return `${sign}${counter}y`case 'quarters':- return `-${counter}q`+ return `${sign}${counter}q`case 'months':- return `-${counter}m`+ return `${sign}${counter}m`case 'weeks':- return `-${counter}w`+ return `${sign}${counter}w`case 'days':- return `-${counter}d`+ return `${sign}${counter}d`case 'hours':- return `-${counter}h`+ return `${sign}${counter}h`case 'minutes':- return `-${counter}M`+ return `${sign}${counter}M`case 'seconds':- return `-${counter}s`+ return `${sign}${counter}s`default:- return `-${counter}d`+ return `${sign}${counter}d`}},],diff --git a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsxindex 3fc6efee00c2..0a928bf79427 100644--- a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx+++ b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx@@ -380,6 +380,7 @@ export function PropertyValue({onChange={setValue}max={10000}isFixedDateMode+ allowFutureRelativeDateOptionsdateOptions={[{key: 'Last 24 hours',diff --git a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsxindex 5f7fff2ae826..a45736c0f918 100644--- a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx+++ b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx@@ -12,7 +12,6 @@ import { PropertyFilterInternalProps } from 'lib/components/PropertyFilters/typeimport {PROPERTY_FILTER_TYPE_TO_TAXONOMIC_FILTER_GROUP_TYPE,isGroupPropertyFilter,- isPropertyFilterWithOperator,propertyFilterTypeToTaxonomicFilterType,sanitizePropertyFilter,} from 'lib/components/PropertyFilters/utils'@@ -203,7 +202,7 @@ export function TaxonomicPropertyFilter({editable={editable}type={filter?.type}propertyKey={filter?.key}- operator={isPropertyFilterWithOperator(filter) ? filter.operator : null}+ operator={filter && 'operator' in filter ? filter.operator : null}value={filter?.value}placeholder="Enter value..."endpoint={diff --git a/frontend/src/lib/components/PropertyFilters/utils.test.ts b/frontend/src/lib/components/PropertyFilters/utils.test.tsindex f183ab1871e9..3452064967a1 100644--- a/frontend/src/lib/components/PropertyFilters/utils.test.ts+++ b/frontend/src/lib/components/PropertyFilters/utils.test.ts@@ -155,6 +155,27 @@ describe('formatPropertyLabel() for behavioral filters', () => {})})+describe('formatPropertyLabel() for account date filters', () => {+ it.each([+ ['-14d', 'created_at > 14 days ago'],+ [['-14d'], 'created_at > 14 days ago'],+ ['14d', 'created_at > 14 days from now'],+ ['+1w', 'created_at > 1 week from now'],+ ])('formats %s as %s', (value, expected) => {+ expect(+ formatPropertyLabel(+ {+ key: 'created_at',+ value,+ type: PropertyFilterType.Account,+ operator: PropertyOperator.IsDateAfter,+ } as unknown as AnyPropertyFilter,+ {}+ ).trim()+ ).toBe(expected)+ })+})+describe('propertyFilterTypeToTaxonomicFilterType()', () => {const baseFilter: AnyPropertyFilter = {type: PropertyFilterType.Event,diff --git a/frontend/src/lib/components/PropertyFilters/utils.ts b/frontend/src/lib/components/PropertyFilters/utils.tsindex 595b719fd3c3..04073e4e389e 100644--- a/frontend/src/lib/components/PropertyFilters/utils.ts+++ b/frontend/src/lib/components/PropertyFilters/utils.ts@@ -1,9 +1,11 @@import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { formatRelativeDateValue } from 'lib/utils/dateFilters'import { isKeyOf } from 'lib/utils/guards'import {allOperatorsMapping,cohortOperatorMap,isOperatorCohort,+ isOperatorDate,isOperatorFlag,isOperatorMulti,} from 'lib/utils/operators'@@ -172,11 +174,19 @@ export function formatPropertyLabel(const label = 'label' in item ? item.label : undefinedconst operator = 'operator' in item ? item.operator : undefinedconst cohortName = 'cohort_name' in item ? item.cohort_name : undefined- const resolvedType = type ?? PropertyFilterType.Event+ const resolvedType = (type ?? PropertyFilterType.Event) as PropertyFilterTypeconst resolvedOperator = operator ?? PropertyOperator.Exactconst taxonomicFilterGroupType = PROPERTY_FILTER_TYPE_TO_TAXONOMIC_FILTER_GROUP_TYPE[resolvedType]const isSingleEmptyString = Array.isArray(value) && value.length === 1 && value[0] === ''+ const relativeDateValue =+ typeof value === 'string' ? value : Array.isArray(value) && value.length === 1 ? value[0] : undefined+ const formattedValue =+ (resolvedType === PropertyFilterType.Account || resolvedType === PropertyFilterType.AccountCustomProperty) &&+ isOperatorDate(resolvedOperator) &&+ typeof relativeDateValue === 'string'+ ? formatRelativeDateValue(relativeDateValue)+ : undefinedif (resolvedType === PropertyFilterType.Cohort) {return (@@ -194,7 +204,7 @@ export function formatPropertyLabel((isOperatorFlag(resolvedOperator)? ` ${allOperatorsMapping[resolvedOperator]}`: ` ${(allOperatorsMapping[resolvedOperator] || '?').split(' ')[0]} ${- isSingleEmptyString ? '(empty string)' : valueFormatter(value) || ''+ formattedValue ?? (isSingleEmptyString ? '(empty string)' : valueFormatter(value) || '')} `))}diff --git a/frontend/src/lib/utils/dateFilters.test.ts b/frontend/src/lib/utils/dateFilters.test.tsindex ce2f74d60672..c5ff6c582cb4 100644--- a/frontend/src/lib/utils/dateFilters.test.ts+++ b/frontend/src/lib/utils/dateFilters.test.ts@@ -5,6 +5,7 @@ import {areDatesValidForInterval,dateFilterToText,dateMapping,+ formatRelativeDateValue,dateStringToDayJs,getDefaultInterval,is12HoursOrLess,@@ -12,6 +13,22 @@ import {} from 'lib/utils/dateFilters'describe('dateFilters utils', () => {+ describe('formatRelativeDateValue()', () => {+ it.each([+ ['-14d', '14 days ago'],+ ['14d', '14 days from now'],+ ['+1w', '1 week from now'],+ ['-1h', '1 hour ago'],+ ['0d', 'now'],+ ])('formats %s as %s', (value, expected) => {+ expect(formatRelativeDateValue(value)).toBe(expected)+ })++ it('returns null for absolute dates', () => {+ expect(formatRelativeDateValue('2026-08-20')).toBeNull()+ })+ })+describe('dateFilterToText()', () => {beforeEach(() => {tk.freeze(new Date('2026-06-15T12:00:00.000Z'))diff --git a/frontend/src/lib/utils/dateFilters.ts b/frontend/src/lib/utils/dateFilters.tsindex 871094cdfda9..0784f8684c40 100644--- a/frontend/src/lib/utils/dateFilters.ts+++ b/frontend/src/lib/utils/dateFilters.ts@@ -220,6 +220,32 @@ export function dateFilterToText(return defaultValue}+const RELATIVE_DATE_VALUE_RE = /^([+-]?)(\d+)([hdwmqyMs])$/+const RELATIVE_DATE_UNIT_LABELS: Record<string, string> = {+ h: 'hour',+ d: 'day',+ w: 'week',+ m: 'month',+ q: 'quarter',+ y: 'year',+ M: 'minute',+ s: 'second',+}++export function formatRelativeDateValue(value: string): string | null {+ const match = RELATIVE_DATE_VALUE_RE.exec(value)+ if (!match) {+ return null+ }+ const [, sign, rawAmount, rawUnit] = match+ const amount = Number.parseInt(rawAmount, 10)+ if (amount === 0) {+ return 'now'+ }+ const unit = RELATIVE_DATE_UNIT_LABELS[rawUnit]+ return `${amount} ${unit}${amount === 1 ? '' : 's'} ${sign === '-' ? 'ago' : 'from now'}`+}+// Converts a dateFrom string ("-2w") into english: "2 weeks"export function dateFromToText(dateFrom: string): string | undefined {const dateOption: (typeof dateOptionsMap)[keyof typeof dateOptionsMap] =diff --git a/products/customer_analytics/backend/logic/account_filters.py b/products/customer_analytics/backend/logic/account_filters.pyindex e695c6943377..8f673d2ff331 100644--- a/products/customer_analytics/backend/logic/account_filters.py+++ b/products/customer_analytics/backend/logic/account_filters.py@@ -1,6 +1,8 @@+import refrom datetime import UTC, datetime, time, timedeltafrom typing import castfrom uuid import UUID+from zoneinfo import ZoneInfofrom django.db.models import Exists, OuterRef, Q, QuerySetfrom django.db.models.fields.json import KeyTextTransform@@ -8,6 +10,7 @@ from django.utils import timezonefrom django.utils.dateparse import parse_date, parse_datetimefrom posthog.models.tagged_item import TaggedItem+from posthog.utils import relative_date_parsefrom products.customer_analytics.backend.facade import contractsfrom products.customer_analytics.backend.models import Account, AccountRelationship, CustomPropertyValue, DisplayType@@ -37,6 +40,9 @@ ACCOUNT_DATETIME_FIELDS = frozenset(contracts.AccountTableField.IGNORED_AT,})+RELATIVE_DATE_VALUE_RE = re.compile(r"[+-]?\d+[hdwmqysHDWMQY](?:Start|End)?")+UTC_TIMEZONE = ZoneInfo("UTC")+ACCOUNT_DIRECT_FIELDS = {contracts.AccountTableField.NAME: "name",contracts.AccountTableField.EXTERNAL_ID: "external_id",@@ -47,14 +53,17 @@ ACCOUNT_DIRECT_FIELDS = {}-def _coerce_datetime_filter_value(value: float | bool | str) -> datetime:+def _coerce_datetime_filter_value(value: float | bool | str, *, timezone_info: ZoneInfo) -> datetime:if not isinstance(value, str):- raise InvalidAccountFilter("Date filters require ISO-8601 values.")+ raise InvalidAccountFilter("Date filters require ISO-8601 or relative date values.")+ if RELATIVE_DATE_VALUE_RE.fullmatch(value):+ relative_value = value.lstrip("+-")+ return relative_date_parse(relative_value, timezone_info, increase=not value.startswith("-"))parsed_datetime = parse_datetime(value)if parsed_datetime is None:parsed_date = parse_date(value)if parsed_date is None:- raise InvalidAccountFilter("Date filters require ISO-8601 values.")+ raise InvalidAccountFilter("Date filters require ISO-8601 or relative date values.")parsed_datetime = datetime.combine(parsed_date, time.min, tzinfo=UTC)elif timezone.is_naive(parsed_datetime):parsed_datetime = timezone.make_aware(parsed_datetime, UTC)@@ -62,7 +71,7 @@ def _coerce_datetime_filter_value(value: float | bool | str) -> datetime:def _apply_account_field_filter(- queryset: QuerySet[Account], filter_: contracts.AccountTableFieldFilter+ queryset: QuerySet[Account], filter_: contracts.AccountTableFieldFilter, *, timezone_info: ZoneInfo) -> QuerySet[Account]:field = filter_.fieldoperator = filter_.operator@@ -109,7 +118,7 @@ def _apply_account_field_filter(if field in ACCOUNT_DATETIME_FIELDS:if len(values) != 1:raise InvalidAccountFilter("Date account field filters require one value.")- target = _coerce_datetime_filter_value(values[0])+ target = _coerce_datetime_filter_value(values[0], timezone_info=timezone_info)if operator == contracts.AccountTableFieldOperator.DATE_EXACT:target_date = target.replace(hour=0, minute=0, second=0, microsecond=0)return queryset.filter(@@ -129,7 +138,7 @@ def _apply_account_field_filter(def _coerce_custom_property_filter_values(- filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType+ filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType, *, timezone_info: ZoneInfo) -> tuple[float | bool | str | datetime, ...]:data_type = DATA_TYPE_BY_DISPLAY_TYPE[display_type]values = filter_.values@@ -161,16 +170,16 @@ def _coerce_custom_property_filter_values(raise InvalidAccountFilter("Boolean custom property filters require true or false values.")return tuple(coerced)if data_type == DataType.DATETIME:- return tuple(_coerce_datetime_filter_value(value) for value in values)+ return tuple(_coerce_datetime_filter_value(value, timezone_info=timezone_info) for value in values)return tuple(str(value) for value in values)def _custom_property_filter_predicate(- filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType+ filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType, *, timezone_info: ZoneInfo) -> tuple[Q, bool]:operator = filter_.operatordata_type = DATA_TYPE_BY_DISPLAY_TYPE[display_type]- values = _coerce_custom_property_filter_values(filter_, display_type)+ values = _coerce_custom_property_filter_values(filter_, display_type, timezone_info=timezone_info)value_field = {DataType.STRING: "value_str",DataType.NUMERIC: "value_num",@@ -250,7 +259,9 @@ def apply_account_filters(team_id: int,filters: tuple[contracts.AccountTableFilter, ...],custom_property_display_types: dict[UUID, DisplayType],+ timezone_info: ZoneInfo | None = None,) -> QuerySet[Account]:+ effective_timezone_info = timezone_info or UTC_TIMEZONEactive_relationships = AccountRelationship.objects.for_team(team_id).filter(account_id=OuterRef("pk"), ended_at__isnull=True, user_id__isnull=False)@@ -273,13 +284,13 @@ def apply_account_filters(elif isinstance(filter_, contracts.AccountTableAccountIdFilter):queryset = queryset.filter(id=filter_.account_id)elif isinstance(filter_, contracts.AccountTableFieldFilter):- queryset = _apply_account_field_filter(queryset, filter_)+ queryset = _apply_account_field_filter(queryset, filter_, timezone_info=effective_timezone_info)elif isinstance(filter_, contracts.AccountTableCustomPropertyFilter):active_values = CustomPropertyValue.objects.for_team(team_id).filter(account_id=OuterRef("pk"), definition_id=filter_.definition_id, is_deleted=False)predicate, negate_exists = _custom_property_filter_predicate(- filter_, custom_property_display_types[filter_.definition_id]+ filter_, custom_property_display_types[filter_.definition_id], timezone_info=effective_timezone_info)matching_values = active_values.filter(predicate)queryset = queryset.filter(~Exists(matching_values) if negate_exists else Exists(matching_values))diff --git a/products/customer_analytics/backend/logic/account_track_rules.py b/products/customer_analytics/backend/logic/account_track_rules.pyindex 95384b691dfa..29dfd3be8fbe 100644--- a/products/customer_analytics/backend/logic/account_track_rules.py+++ b/products/customer_analytics/backend/logic/account_track_rules.py@@ -4,6 +4,7 @@ from dataclasses import dataclassfrom datetime import datetimefrom typing import Anyfrom uuid import UUID+from zoneinfo import ZoneInfofrom django.db import transactionfrom django.db.models import Count, OuterRef, Q, QuerySet, Subquery@@ -15,6 +16,7 @@ from posthog.dataclasses import frozenfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.team import Teamfrom posthog.models.user import Userfrom products.customer_analytics.backend.facade import contracts@@ -70,6 +72,7 @@ class AccountTrackRuleRunError(ValueError):class ParsedAccountTrackRules:config: contracts.AccountTrackRulesConfigcustom_property_display_types: dict[UUID, DisplayType]+ timezone_info: ZoneInfo@dataclass(frozen=True)@@ -261,7 +264,11 @@ def parse_account_track_rules(team_id: int, raw_config: Any) -> ParsedAccountTraenabled=raw_config["enabled"],groups=tuple(groups),)- parsed = ParsedAccountTrackRules(config=config, custom_property_display_types=display_types)+ parsed = ParsedAccountTrackRules(+ config=config,+ custom_property_display_types=display_types,+ timezone_info=Team.objects.only("timezone").get(pk=team_id).timezone_info,+ )_validate_compiler_inputs(team_id, parsed)return parsed@@ -298,6 +305,7 @@ def _validate_compiler_inputs(team_id: int, parsed: ParsedAccountTrackRules) ->team_id=team_id,filters=_group_filters(group),custom_property_display_types=parsed.custom_property_display_types,+ timezone_info=parsed.timezone_info,)except (InvalidAccountFilter, TypeError) as error:raise AccountTrackRuleValidationError([str(error)]) from error@@ -315,6 +323,7 @@ def matching_accounts_queryset(team_id=team_id,filters=_group_filters(group),custom_property_display_types=parsed.custom_property_display_types,+ timezone_info=parsed.timezone_info,)matching_groups |= Q(id__in=Subquery(group_matches.values("id")))return queryset.filter(matching_groups)diff --git a/products/customer_analytics/backend/test/test_account_track_rules.py b/products/customer_analytics/backend/test/test_account_track_rules.pyindex 33e144b0810c..6b0bb20df74f 100644--- a/products/customer_analytics/backend/test/test_account_track_rules.py+++ b/products/customer_analytics/backend/test/test_account_track_rules.py@@ -10,6 +10,7 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import AsyncMock, MagicMock, patch+from parameterized import parameterizedfrom rest_framework import statusfrom temporalio import activityfrom temporalio.client import ScheduleActionStartWorkflow, ScheduleOverlapPolicy, ScheduleState@@ -34,6 +35,7 @@ from products.customer_analytics.backend.logic.account_track_rules import (update_account_track_rules,)from products.customer_analytics.backend.models import (+ Account,AccountTrackRuleRun,AccountTrackRuleRunStatus,AccountTrackRuleRunTrigger,@@ -446,6 +448,84 @@ class TestAccountTrackRuleLogic(AccountTrackRulesTestMixin, BaseTest):churned.refresh_from_db()assert churned.ignored_at == datetime(2025, 1, 4, tzinfo=UTC)+ @parameterized.expand([("past", "-30d", {"Recent"}), ("future", "14d", set())])+ def test_preview_evaluates_relative_date_conditions(+ self, _name: str, relative_value: str, expected_names: set[str]+ ) -> None:+ recent = create_account(team_id=self.team.id, name="Recent")+ older = create_account(team_id=self.team.id, name="Older")+ Account.objects.for_team(self.team.id).filter(id=recent.id).update(created_at=datetime(2026, 8, 1, tzinfo=UTC))+ Account.objects.for_team(self.team.id).filter(id=older.id).update(created_at=datetime(2026, 7, 1, tzinfo=UTC))+ self.save_config(+ {+ "schema_version": 1,+ "version": 1,+ "enabled": True,+ "groups": [+ {+ "conditions": [+ {+ "field": {"kind": "account_field", "field": "created_at"},+ "operator": "is_date_after",+ "values": [relative_value],+ }+ ]+ }+ ],+ }+ )++ preview = preview_account_track_rules(self.team.id)++ assert preview.tracked == len(expected_names)+ assert preview.ignored == 2 - len(expected_names)+ assert {sample.name for sample in preview.tracked_samples} == expected_names++ def test_preview_evaluates_future_relative_date_custom_property_conditions(self) -> None:+ definition = create_custom_property_definition(+ team_id=self.team.id,+ name="Renewal date",+ display_type=DisplayType.DATETIME,+ )+ later = create_account(team_id=self.team.id, name="Later")+ sooner = create_account(team_id=self.team.id, name="Sooner")+ CustomPropertyValue.objects.unscoped().create(+ team=self.team,+ account=later,+ definition=definition,+ value_datetime=datetime(2026, 9, 1, tzinfo=UTC),+ )+ CustomPropertyValue.objects.unscoped().create(+ team=self.team,+ account=sooner,+ definition=definition,+ value_datetime=datetime(2026, 8, 25, tzinfo=UTC),+ )+ self.save_config(+ {+ "schema_version": 1,+ "version": 1,+ "enabled": True,+ "groups": [+ {+ "conditions": [+ {+ "field": {"kind": "custom_property", "definition_id": str(definition.id)},+ "operator": "is_date_after",+ "values": ["+10d"],+ }+ ]+ }+ ],+ }+ )++ preview = preview_account_track_rules(self.team.id)++ assert preview.tracked == 1+ assert preview.ignored == 1+ assert {sample.name for sample in preview.tracked_samples} == {"Later"}+def test_apply_batches_preserve_ignored_timestamps_and_restore_matches(self) -> None:definition, paying, vip, unmatched, ignored, churned = self.create_rule_fixtures()original_ignored_at = ignored.ignored_at@@ -690,6 +770,28 @@ class TestAccountTrackRuleLogic(AccountTrackRulesTestMixin, BaseTest):with pytest.raises(AccountTrackRuleValidationError):preview_account_track_rules(self.team.id)+ for relative_value in ["d", "-d", "+d", "y", "mStart"]:+ config = {+ "schema_version": 1,+ "version": 1,+ "enabled": False,+ "groups": [+ {+ "conditions": [+ {+ "field": {"kind": "account_field", "field": "created_at"},+ "operator": "is_date_after",+ "values": [relative_value],+ }+ ]+ }+ ],+ }+ with self.subTest(relative_value=relative_value):+ self.save_config(config)+ with pytest.raises(AccountTrackRuleValidationError):+ preview_account_track_rules(self.team.id)+def test_run_creation_is_idempotent_and_workflow_id_is_per_team(self) -> None:definition, *_ = self.create_rule_fixtures()self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsxindex 5ab34e28d769..46dc5d4b3d6b 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx@@ -138,6 +138,9 @@ export function AccountTrackRules(): JSX.Element {scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,})+ const trackRulePropertyDefinitions = [...TRACK_RULE_ACCOUNT_FIELDS, ...customPropertyTaxonomicOptions].map(+ ({ id, property_type }) => ({ id, name: id, property_type })+ )const confirmRun = (): void => {if (!config?.enabled || hasUnsavedChanges || !canRun) {@@ -222,6 +225,8 @@ export function AccountTrackRules(): JSX.Element {[TaxonomicFilterGroupType.AccountCustomProperties]: customPropertyTaxonomicOptions,}}operatorAllowlist={ACCOUNT_FILTER_OPERATOR_ALLOWLIST}+ propertyDefinitionsOverride={trackRulePropertyDefinitions}+ allowRelativeDateOptionsstaticValueOptions={accountFilterStaticValueOptions}editable={!restrictionReason}disabledReason={restrictionReason ?? undefined}