OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix: cohort filters and view funnel profiles with breakdowns
Carl-Gerhard Lindesvärd604a5698e3d8
diff --git a/apps/start/src/components/filters/FiltersBuilder.tsx b/apps/start/src/components/filters/FiltersBuilder.tsxindex 64ace316a..5019946cb 100644--- a/apps/start/src/components/filters/FiltersBuilder.tsx+++ b/apps/start/src/components/filters/FiltersBuilder.tsx@@ -45,29 +45,33 @@ export function FiltersBuilder({onChange(value.filter((f) => f.id !== target.id));};- const addFilter = (action: {- value: string;- cohortId?: string;- }) => {- // Use the property name as the id so the URL serializer can encode the- // filter under a stable, human-readable key. A random id would survive- // round-trips through the URL but would replace the human-readable- // `name` on reload — see useTableFilters serialize/parse logic.- const next: IChartEventFilter = action.cohortId- ? {- id: action.value,- name: action.value,+ const addFilter = (action: { value: string }) => {+ if (action.value === 'cohort') {+ const hasCohort = value.some(+ (f) => f.operator === 'inCohort' || f.operator === 'notInCohort',+ );+ if (hasCohort) return;+ onChange([+ ...value,+ {+ id: 'cohort',+ name: 'cohort',operator: 'inCohort',value: [],- cohortId: action.cohortId,- }- : {- id: action.value,- name: action.value,- operator: 'is',- value: [],- };- onChange([...value, next]);+ cohortIds: [],+ },+ ]);+ return;+ }+ onChange([+ ...value,+ {+ id: action.value,+ name: action.value,+ operator: 'is',+ value: [],+ },+ ]);};return (@@ -87,11 +91,9 @@ export function FiltersBuilder({setFilter({ ...original, operator })}onChangeCohort={(cohortIds, original) => {- const firstId = cohortIds[0];setFilter({...original,- name: firstId ? `cohort:${firstId}` : original.name,- cohortId: firstId,+ cohortId: cohortIds[0],cohortIds,});}}diff --git a/apps/start/src/components/filters/TableFilterPills.tsx b/apps/start/src/components/filters/TableFilterPills.tsxindex e6b5aac61..001e777dd 100644--- a/apps/start/src/components/filters/TableFilterPills.tsx+++ b/apps/start/src/components/filters/TableFilterPills.tsx@@ -38,7 +38,7 @@ const SESSION_LABELS: Record<string, string> = {};function humanizeFilterName(name: string): string {- if (name.startsWith('cohort:')) return 'Cohort';+ if (name === 'cohort' || name.startsWith('cohort:')) return 'Cohort';if (SESSION_LABELS[name]) return SESSION_LABELS[name]!;if (name.startsWith('profile.')) {const rest = name.replace(/^profile\./, '');diff --git a/apps/start/src/components/overview/filters/overview-filters-buttons.tsx b/apps/start/src/components/overview/filters/overview-filters-buttons.tsxindex 966a30dc0..886b850f8 100644--- a/apps/start/src/components/overview/filters/overview-filters-buttons.tsx+++ b/apps/start/src/components/overview/filters/overview-filters-buttons.tsx@@ -1,7 +1,9 @@import { Button } from '@/components/ui/button';import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';+import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';import { FilterOperatorSelect } from '@/components/report/sidebar/filters/FilterOperatorSelect';import { useAppParams } from '@/hooks/use-app-params';+import { useCohorts } from '@/hooks/use-cohorts';import {useEventQueryFilters,useEventQueryNamesFilter,@@ -12,9 +14,10 @@ import type { OverviewFiltersProps } from '@/modals/overview-filters';import { getPropertyLabel } from '@/translations/properties';import { cn } from '@/utils/cn';import { operators } from '@openpanel/constants';-import type {- IChartEventFilter,- IChartEventFilterOperator,+import {+ getCohortIds,+ type IChartEventFilter,+ type IChartEventFilterOperator,} from '@openpanel/validation';import { FilterIcon, X } from 'lucide-react';import type { Options as NuqsOptions } from 'nuqs';@@ -49,6 +52,85 @@ interface FilterPillProps {onChangeValue: (value: string[]) => void;}+interface CohortFilterPillProps {+ filter: IChartEventFilter;+ nuqsOptions?: NuqsOptions;+ onRemove: () => void;+ onChangeOperator: (operator: IChartEventFilterOperator) => void;+ onChangeCohorts: (cohortIds: string[]) => void;+}++function CohortFilterPill({+ filter,+ nuqsOptions,+ onRemove,+ onChangeOperator,+ onChangeCohorts,+}: CohortFilterPillProps) {+ const { projectId } = useAppParams();+ const cohorts = useCohorts({ projectId, includeCount: false });+ const selectedIds = getCohortIds(filter);+ const cohortItems = cohorts.map((c) => ({ value: c.id, label: c.name }));+ const valueLabel =+ selectedIds+ .map((id) => cohorts.find((c) => c.id === id)?.name)+ .filter(Boolean)+ .join(', ');++ return (+ <div className="flex items-stretch text-sm border rounded-md overflow-hidden h-8">+ <button+ type="button"+ onClick={() => pushModal('OverviewFilters', { nuqsOptions })}+ className="px-2 hover:bg-accent transition-colors cursor-pointer"+ >+ Cohort+ </button>+ <DropdownMenuComposed+ onChange={onChangeOperator}+ items={[+ { value: 'inCohort', label: 'In cohort' },+ { value: 'notInCohort', label: 'Not in cohort' },+ ]}+ label="Operator"+ >+ <button+ type="button"+ className="px-2 opacity-50 lowercase hover:opacity-100 hover:bg-accent transition-colors border-l cursor-pointer"+ >+ {filter.operator === 'inCohort' ? 'in cohort' : 'not in cohort'}+ </button>+ </DropdownMenuComposed>+ <ComboboxAdvanced+ items={cohortItems}+ value={selectedIds}+ onChange={(next) =>+ onChangeCohorts(+ next.filter((id): id is string => typeof id === 'string'),+ )+ }+ >+ <button+ type="button"+ className="px-2 font-semibold hover:bg-accent transition-colors border-l cursor-pointer max-w-40 truncate"+ >+ {valueLabel || (+ <span className="opacity-40 font-normal italic">pick cohort</span>+ )}+ </button>+ </ComboboxAdvanced>+ <button+ type="button"+ onClick={onRemove}+ className="px-2 hover:bg-destructive hover:text-destructive-foreground transition-colors border-l cursor-pointer"+ aria-label="Remove filter"+ >+ <X className="size-3" />+ </button>+ </div>+ );+}+function FilterPill({filter,nuqsOptions,@@ -125,11 +207,28 @@ export function OverviewFiltersButtons({nuqsOptions,}: OverviewFiltersButtonsProps) {const [events, setEvents] = useEventQueryNamesFilter(nuqsOptions);- const [filters, setFilter, _setFilters, removeFilter] =+ const [filters, setFilter, setFilters, removeFilter] =useEventQueryFilters(nuqsOptions);if (filters.length === 0 && events.length === 0) return null;+ const updateCohortFilter = (updated: IChartEventFilter) => {+ setFilters((prev) =>+ prev.map((f) =>+ f.name === updated.name+ ? {+ id: updated.id ?? updated.name,+ name: updated.name,+ operator: updated.operator,+ value: updated.value.map((v) => (v == null ? '' : String(v))),+ ...(updated.cohortIds ? { cohortIds: updated.cohortIds } : {}),+ ...(updated.cohortId ? { cohortId: updated.cohortId } : {}),+ }+ : f,+ ),+ );+ };+return (<div className={cn('flex flex-wrap gap-2', className)}>{events.map((event) => (@@ -143,20 +242,44 @@ export function OverviewFiltersButtons({<strong className="font-semibold">{event}</strong></Button>))}- {filters.map((filter) => (- <FilterPill- key={filter.name}- filter={filter}- nuqsOptions={nuqsOptions}- onRemove={() => removeFilter(filter.name)}- onChangeOperator={(operator) =>- setFilter(filter.name, filter.value, operator)- }- onChangeValue={(value) =>- setFilter(filter.name, value, filter.operator)- }- />- ))}+ {filters.map((filter) => {+ const isCohort =+ filter.operator === 'inCohort' || filter.operator === 'notInCohort';+ if (isCohort) {+ return (+ <CohortFilterPill+ key={filter.name}+ filter={filter}+ nuqsOptions={nuqsOptions}+ onRemove={() => removeFilter(filter.name)}+ onChangeOperator={(operator) =>+ updateCohortFilter({ ...filter, operator })+ }+ onChangeCohorts={(cohortIds) =>+ updateCohortFilter({+ ...filter,+ cohortId: cohortIds[0],+ cohortIds,+ })+ }+ />+ );+ }+ return (+ <FilterPill+ key={filter.name}+ filter={filter}+ nuqsOptions={nuqsOptions}+ onRemove={() => removeFilter(filter.name)}+ onChangeOperator={(operator) =>+ setFilter(filter.name, filter.value, operator)+ }+ onChangeValue={(value) =>+ setFilter(filter.name, value, filter.operator)+ }+ />+ );+ })}</div>);}diff --git a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsxindex 146c3fe3b..54c52e713 100644--- a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx+++ b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx@@ -22,7 +22,6 @@ import {} from '@/components/ui/dropdown-menu';import { Input } from '@/components/ui/input';import { useAppParams } from '@/hooks/use-app-params';-import { useCohorts } from '@/hooks/use-cohorts';import { useEventProperties } from '@/hooks/use-event-properties';import { useTRPC } from '@/integrations/trpc/react';@@ -30,7 +29,6 @@ export type PropertiesComboboxAction = {value: string;label: string;description: string;- cohortId?: string;};export type PropertiesComboboxCategory =@@ -40,7 +38,7 @@ export type PropertiesComboboxCategory =| 'cohort'| 'session';-type State = 'index' | PropertiesComboboxCategory;+type State = 'index' | Exclude<PropertiesComboboxCategory, 'cohort'>;interface PropertiesComboboxProps {event?: IChartEvent;@@ -49,7 +47,6 @@ interface PropertiesComboboxProps {exclude?: string[];include?: string[];categories?: PropertiesComboboxCategory[];- isBreakdown?: boolean;}/**@@ -129,7 +126,6 @@ export function PropertiesCombobox({categories = DEFAULT_CATEGORIES,exclude = [],include = [],- isBreakdown = false,}: PropertiesComboboxProps) {const { projectId } = useAppParams();const trpc = useTRPC();@@ -144,14 +140,16 @@ export function PropertiesCombobox({{ enabled: categories.includes('group') },),);- const cohorts = useCohorts(- { projectId, includeCount: false },- { enabled: categories.includes('cohort') },- );- /** Skip the index screen when only one category is reachable. */+ /**+ * Skip the index screen when only one category is reachable — except for+ * `cohort`, which has no sub-list (clicking it emits a generic cohort+ * filter action directly).+ */const initialState: State =- categories.length === 1 ? categories[0]! : 'index';+ categories.length === 1 && categories[0] !== 'cohort'+ ? (categories[0] as Exclude<PropertiesComboboxCategory, 'cohort'>)+ : 'index';const [state, setState] = useState<State>(initialState);const [search, setSearch] = useState('');@@ -220,15 +218,6 @@ export function PropertiesCombobox({onSelect(action);};- const cohortActions: PropertiesComboboxAction[] = cohorts.map((cohort) => ({- value: `cohort:${cohort.id}`,- label: cohort.name,- description: cohort.description- ? cohort.description- : `${cohort.profileCount ?? 0} members`,- cohortId: cohort.id,- }));-const showBackButton = categories.length > 1;const renderIndex = () => {@@ -275,15 +264,11 @@ export function PropertiesCombobox({className="group justify-between gap-2"onClick={(e) => {e.preventDefault();- if (isBreakdown) {- handleSelect({- value: 'cohort',- label: 'Cohorts',- description: 'All cohorts',- });- } else {- handleStateChange('cohort');- }+ handleSelect({+ value: 'cohort',+ label: 'Cohorts',+ description: 'All cohorts',+ });}}>Cohorts@@ -402,17 +387,6 @@ export function PropertiesCombobox({{renderActionList(groupActions)}</motion.div>)}- {state === 'cohort' && (- <motion.div- animate={{ opacity: 1, x: 0 }}- exit={{ opacity: 0, x: direction === 'forward' ? -20 : 20 }}- initial={{ opacity: 0, x: direction === 'forward' ? 20 : -20 }}- key="cohort"- transition={{ duration: 0.05 }}- >- {renderActionList(cohortActions)}- </motion.div>- )}{state === 'session' && (<motion.divanimate={{ opacity: 1, x: 0 }}diff --git a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsxindex 5b9a8da91..142826700 100644--- a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx+++ b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx@@ -39,7 +39,6 @@ export function ReportBreakdowns() {<div className="flex items-center gap-2 p-2 px-4"><ColorSquare>{index}</ColorSquare><PropertiesCombobox- isBreakdowncategories={['event', 'profile', 'group', 'cohort']}onSelect={(action) => {dispatch(@@ -73,7 +72,6 @@ export function ReportBreakdowns() {})}<PropertiesCombobox- isBreakdowncategories={['event', 'profile', 'group', 'cohort']}onSelect={(action) => {dispatch(diff --git a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsxindex 87b0d2f3e..5d51f4394 100644--- a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx+++ b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx@@ -73,18 +73,28 @@ export function ReportSeriesItem({event={chartEvent}categories={['event', 'profile', 'group', 'cohort']}onSelect={(action) => {+ const isCohortAction = action.value === 'cohort';+ if (+ isCohortAction &&+ chartEvent.filters.some(+ (f) =>+ f.operator === 'inCohort' || f.operator === 'notInCohort',+ )+ ) {+ return;+ }dispatch(changeEvent({...chartEvent,filters: [...chartEvent.filters,- action.cohortId+ isCohortAction? {id: shortId(),- name: action.value,+ name: 'cohort',operator: 'inCohort',value: [],- cohortId: action.cohortId,+ cohortIds: [],}: {id: shortId(),diff --git a/apps/start/src/integrations/tanstack-query/root-provider.tsx b/apps/start/src/integrations/tanstack-query/root-provider.tsxindex db14bd122..81ca44ff7 100644--- a/apps/start/src/integrations/tanstack-query/root-provider.tsx+++ b/apps/start/src/integrations/tanstack-query/root-provider.tsx@@ -8,7 +8,7 @@ import { useMemo } from 'react';import superjson from 'superjson';import { TRPCProvider } from '@/integrations/trpc/react';-const DEFAULT_RETRY_COUNT = 3;+const DEFAULT_RETRY_COUNT = 1;function shouldRetryQuery(failureCount: number, error: unknown) {if (error instanceof TRPCClientError) {diff --git a/apps/start/src/modals/overview-filters.tsx b/apps/start/src/modals/overview-filters.tsxindex 48f5b19a2..2336ccc2f 100644--- a/apps/start/src/modals/overview-filters.tsx+++ b/apps/start/src/modals/overview-filters.tsx@@ -1,3 +1,4 @@+import { PureCohortFilterItem } from '@/components/report/sidebar/filters/CohortFilterItem';import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';import { Button } from '@/components/ui/button';import { Combobox } from '@/components/ui/combobox';@@ -47,10 +48,31 @@ export default function OverviewFilters({mode,}: OverviewFiltersProps) {const { projectId } = useAppParams();- const [filters, setFilter] = useEventQueryFilters(nuqsOptions);+ const [filters, setFilter, setFilters, removeFilter] =+ useEventQueryFilters(nuqsOptions);const [event, setEvent] = useEventQueryNamesFilter(nuqsOptions);const eventNames = useEventNames({ projectId, anyEvents: false });const selectedFilters = filters.filter((filter) => filter.value[0] !== null);++ const isCohortFilter = (filter: IChartEventFilter) =>+ filter.operator === 'inCohort' || filter.operator === 'notInCohort';++ const updateCohortFilter = (updated: IChartEventFilter) => {+ setFilters((prev) =>+ prev.map((f) =>+ f.name === updated.name+ ? {+ id: updated.id ?? updated.name,+ name: updated.name,+ operator: updated.operator,+ value: updated.value.map((v) => (v == null ? '' : String(v))),+ ...(updated.cohortIds ? { cohortIds: updated.cohortIds } : {}),+ ...(updated.cohortId ? { cohortId: updated.cohortId } : {}),+ }+ : f,+ ),+ );+ };return (<SheetContent className="[&>button.absolute]:hidden"><ModalHeader title="Filters" />@@ -92,6 +114,26 @@ export default function OverviewFilters({</div>)}{selectedFilters.map((filter) => {+ if (isCohortFilter(filter)) {+ return (+ <PureCohortFilterItem+ className="border-t p-4 first:border-0"+ key={filter.id ?? filter.name}+ filter={filter}+ onRemove={(target) => removeFilter(target.name)}+ onChangeOperator={(operator, original) =>+ updateCohortFilter({ ...original, operator })+ }+ onChangeCohort={(cohortIds, original) =>+ updateCohortFilter({+ ...original,+ cohortId: cohortIds[0],+ cohortIds,+ })+ }+ />+ );+ }return (<PureFilterItemclassName="border-t p-4 first:border-0"@@ -131,6 +173,23 @@ export default function OverviewFilters({]}onSelect={(action) => {+ if (action.value === 'cohort') {+ // Only one cohort filter at a time; OR-semantics live inside+ // the filter's cohortIds array.+ const hasCohort = filters.some(isCohortFilter);+ if (hasCohort) return;+ setFilters((prev) => [+ ...prev,+ {+ id: 'cohort',+ name: 'cohort',+ operator: 'inCohort',+ value: [],+ cohortIds: [],+ },+ ]);+ return;+ }setFilter(action.value, [], 'is');}}>diff --git a/apps/start/src/modals/table-filters.tsx b/apps/start/src/modals/table-filters.tsxindex ceaee196b..b6bb9f17e 100644--- a/apps/start/src/modals/table-filters.tsx+++ b/apps/start/src/modals/table-filters.tsx@@ -54,24 +54,37 @@ export default function TableFilters({setFilters(filters.filter((f) => f.id !== target.id));};- const addFilter = (action: { value: string; cohortId?: string }) => {- // Use the property name as the id so the URL serializer (which encodes- // by name) round-trips cleanly on reload.- const next: IChartEventFilter = action.cohortId- ? {- id: action.value,- name: action.value,+ const addFilter = (action: { value: string }) => {+ if (action.value === 'cohort') {+ // Only one cohort filter at a time — multi-cohort OR semantics already+ // live inside a single filter's cohortIds array.+ const hasCohort = filters.some(+ (f) => f.operator === 'inCohort' || f.operator === 'notInCohort',+ );+ if (hasCohort) return;+ setFilters([+ ...filters,+ {+ id: 'cohort',+ name: 'cohort',operator: 'inCohort',value: [],- cohortId: action.cohortId,- }- : {- id: action.value,- name: action.value,- operator: 'is',- value: [],- };- setFilters([...filters, next]);+ cohortIds: [],+ },+ ]);+ return;+ }+ // Use the property name as the id so the URL serializer (which encodes+ // by name) round-trips cleanly on reload.+ setFilters([+ ...filters,+ {+ id: action.value,+ name: action.value,+ operator: 'is',+ value: [],+ },+ ]);};return (@@ -100,16 +113,13 @@ export default function TableFilters({setFilter({ ...original, operator })}onChangeCohort={(cohortIds, original) => {- // Keep `id` stable so the setFilter helper (which matches- // by id) still finds this row. URL serializes by `name`,- // which we update — on reload the parser will resync id- // from the name. Write both cohort fields so legacy- // consumers reading `cohortId` keep working.- const firstId = cohortIds[0];+ // Write both cohort fields so legacy consumers reading+ // `cohortId` keep working. Name stays stable as `cohort`+ // (new filters) or `cohort:<id>` (legacy saved filters)+ // — the URL parser reads the cohortIds segment first.setFilter({...original,- name: firstId ? `cohort:${firstId}` : original.name,- cohortId: firstId,+ cohortId: cohortIds[0],cohortIds,});}}diff --git a/packages/db/src/services/chart.service.ts b/packages/db/src/services/chart.service.tsindex 8cefdeb03..839bb3655 100644--- a/packages/db/src/services/chart.service.ts+++ b/packages/db/src/services/chart.service.ts@@ -204,20 +204,16 @@ export function buildAllCohortsLabelExpr(return `transform(${alias}.cohort_id, [${ids}], [${names}], 'Unknown')`;}-export function collectCohortIds(- filters: IChartEventFilter[],+/**+ * Cohort IDs that need a `cohort_<id>` JOIN alias to be wired up by the+ * caller. After filter SQL became self-contained, only cohort *breakdowns*+ * require the JOIN — they reference `cohort_<id>.profile_id` in their+ * SELECT expression via `getSelectPropertyKey`.+ */+export function collectBreakdownCohortIds(breakdowns: IChartBreakdown[],): string[] {const ids = new Set<string>();- for (const filter of filters) {- // Collect from both `cohortId` (legacy) and `cohortIds` (multi-value).- // Only single-cohort filters use the CTE join path — multi-cohort- // filters compile to a direct subselect in getEventFiltersWhereClause.- const filterCohortIds = getCohortIds(filter);- if (filterCohortIds.length === 1) {- ids.add(filterCohortIds[0]!);- }- }for (const breakdown of breakdowns) {const id = extractCohortId(breakdown.name);if (id) {@@ -428,7 +424,7 @@ export async function getChartSql({const hasAllCohortsBreakdown =requestedAllCohortsBreakdown && allCohorts.length > 0;- const cohortIds = collectCohortIds(event.filters, breakdowns);+ const cohortIds = collectBreakdownCohortIds(breakdowns);const cohortMetadata = await fetchCohortsMetadata(cohortIds);// Add CTE + JOIN for "all cohorts" breakdown@@ -846,7 +842,7 @@ export async function getAggregateChartSql({const hasAllCohortsBreakdown =requestedAllCohortsBreakdown && allCohorts.length > 0;- const cohortIds = collectCohortIds(event.filters, breakdowns);+ const cohortIds = collectBreakdownCohortIds(breakdowns);const cohortMetadata = await fetchCohortsMetadata(cohortIds);// Add CTE + JOIN for "all cohorts" breakdown@@ -1155,28 +1151,20 @@ export function getEventFiltersWhereClause((operator === 'inCohort' || operator === 'notInCohort') &&projectId) {+ // Self-contained membership subselect — no caller JOIN wiring needed.+ // Cohort filters and cohort breakdowns are decoupled: the breakdown+ // path (getSelectPropertyKey) still uses a JOIN alias for SELECT+ // expressions, but filters never depend on it.const cohortIds = getCohortIds(filter);if (cohortIds.length === 0) return;-- if (cohortIds.length === 1) {- // Preserve the original CTE-join path for the single-cohort case- // (collectCohortIds wires up the CTE for us). Behaviour for saved- // reports with `cohortId: string` is unchanged.- const single = cohortIds[0]!;- where[id] =- operator === 'notInCohort'- ? `empty(${getCohortAlias(single)}.profile_id)`- : `notEmpty(${getCohortAlias(single)}.profile_id)`;- return;- }-- // Multi-cohort: compile to a direct subselect against cohort_members.- // No CTE join needed — saves an unnecessary plan for the ad-hoc case.+ const profileIdExpr = eventsAlias+ ? `${eventsAlias}.profile_id`+ : 'profile_id';+ const op = operator === 'notInCohort' ? 'NOT IN' : 'IN';const escapedIds = cohortIds.map((c) => sqlstring.escape(c)).join(', ');- const op = operator === 'notInCohort' ? 'NOT IN' : 'IN';- where[id] = `e.profile_id ${op} (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;+ where[id] = `${profileIdExpr} ${op} (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;return;}diff --git a/packages/db/src/services/conversion.service.ts b/packages/db/src/services/conversion.service.tsindex 5d3724ac0..e25961066 100644--- a/packages/db/src/services/conversion.service.ts+++ b/packages/db/src/services/conversion.service.ts@@ -6,7 +6,7 @@ import { TABLE_NAMES, ch } from '../clickhouse/client';import { clix } from '../clickhouse/query-builder';import {buildInlineCohortJoin,- collectCohortIds,+ collectBreakdownCohortIds,extractCohortId,fetchCohortsMetadata,getEventFiltersWhereClause,@@ -40,10 +40,7 @@ export class ConversionService {// can't be resolved against the events schema.breakdowns = breakdowns.filter((b) => isKnownEventField(b.name));- const allFilters = series.flatMap((s) =>- s.type === 'event' ? s.filters ?? [] : [],- );- const cohortIds = collectCohortIds(allFilters, breakdowns);+ const cohortIds = collectBreakdownCohortIds(breakdowns);const cohortMetadata = await fetchCohortsMetadata(cohortIds);const cohortJoinsSql = cohortIds.map((id) => buildInlineCohortJoin(id, projectId, 'events'))diff --git a/packages/db/src/services/event.service.ts b/packages/db/src/services/event.service.tsindex 94e433bff..17775b735 100644--- a/packages/db/src/services/event.service.ts+++ b/packages/db/src/services/event.service.ts@@ -646,7 +646,7 @@ export async function getEventList(options: GetEventListOptions) {if (filters) {sb.where = {...sb.where,- ...getEventFiltersWhereClause(filters, projectId),+ ...getEventFiltersWhereClause(filters, projectId, 'e'),};// Join profiles table if any filter uses profile fields@@ -730,7 +730,7 @@ export async function getEventsCount({if (filters) {sb.where = {...sb.where,- ...getEventFiltersWhereClause(filters, projectId),+ ...getEventFiltersWhereClause(filters, projectId, 'e'),};// Join profiles table if any filter uses profile fieldsdiff --git a/packages/db/src/services/funnel.service.ts b/packages/db/src/services/funnel.service.tsindex 233f6f5f7..de1379610 100644--- a/packages/db/src/services/funnel.service.ts+++ b/packages/db/src/services/funnel.service.ts@@ -8,7 +8,7 @@ import { clix } from '../clickhouse/query-builder';import { createSqlBuilder } from '../sql-builder';import {buildInlineCohortJoin,- collectCohortIds,+ collectBreakdownCohortIds,extractCohortId,fetchCohortsMetadata,getEventFiltersWhereClause,@@ -258,8 +258,7 @@ export class FunnelService {const needsGroupArrayJoin =anyFilterOnGroup || anyBreakdownOnGroup || funnelGroup === 'group';- const allFilters = eventSeries.flatMap((e) => e.filters ?? []);- const cohortIds = collectCohortIds(allFilters, breakdowns);+ const cohortIds = collectBreakdownCohortIds(breakdowns);const cohortMetadata = await fetchCohortsMetadata(cohortIds);// Create the funnel CTE (session-level)diff --git a/packages/trpc/src/routers/chart.ts b/packages/trpc/src/routers/chart.tsindex 8a4c23e04..2a7e3a417 100644--- a/packages/trpc/src/routers/chart.ts+++ b/packages/trpc/src/routers/chart.ts@@ -386,6 +386,13 @@ export const chartRouter = createTRPCRouter({const res = await query.execute();values.push(...res.map((r) => String(r.values)).filter(Boolean));+ } else if (property === 'cohort' || property.startsWith('cohort:')) {+ // Cohort filters use a dedicated cohort multi-select on the client+ // (ComboboxAdvanced over all cohorts) — values aren't sourced from+ // an event-column distinct query. Without this guard, the events+ // SELECT would emit a literal `cohort:<uuid>` identifier and crash+ // with a ClickHouse syntax error.+ return { values: [] };} else {// Normalize bare utm_* names to `properties.__query.utm_*` and rewrite// camelCase aliases (`referrerName`) to their snake_case columns.@@ -961,14 +968,22 @@ export const chartRouter = createTRPCRouter({group,});- // Check for profile filters and add profile join if needed+ // Profile JOIN must cover both profile filters AND profile breakdowns —+ // breakdownSelects reference `profile.properties[...]` etc. via+ // getSelectPropertyKey, so the alias has to exist in scope even when+ // no filter touches the profiles table. Mirrors the same guard in+ // funnelService.getFunnel.const profileFilters = funnelService.getProfileFilters(eventSeries as IChartEvent[]);- if (profileFilters.length > 0) {- const fieldsToSelect = uniq(- profileFilters.map((f) => f.split('.')[0])- ).join(', ');+ const profileBreakdownNames = breakdowns+ .filter((b) => b.name.startsWith('profile.'))+ .map((b) => b.name.replace('profile.', ''));+ if (profileFilters.length > 0 || profileBreakdownNames.length > 0) {+ const fieldsToSelect = uniq([+ ...profileFilters.map((f) => f.split('.')[0]!),+ ...profileBreakdownNames.map((f) => f.split('.')[0]!),+ ]).join(', ');funnelCte.leftJoin(`(SELECT id, ${fieldsToSelect} FROM ${TABLE_NAMES.profiles} FINAL WHERE project_id = ${sqlstring.escape(projectId)}) as profile`,'profile.id = events.profile_id'