:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): let cohort branch split evenly across any number of branches (#75757)
jake sciotto25d710bc95a2
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepRandomCohortBranch.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepRandomCohortBranch.tsxindex 3e99bb1ab880..681da15915fd 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepRandomCohortBranch.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepRandomCohortBranch.tsx@@ -1,6 +1,6 @@import { Node } from '@xyflow/react'import { useActions, useValues } from 'kea'-import { useMemo } from 'react'+import { useMemo, useState } from 'react'import { IconBalance, IconPlus, IconX } from '@posthog/icons'@@ -11,7 +11,17 @@ import { LemonLabel } from 'lib/lemon-ui/LemonLabel'import { hogFlowEditorLogic } from '../hogFlowEditorLogic'import { HogFlow, HogFlowAction } from '../types'import { StepSchemaErrors } from './components/StepSchemaErrors'-import { useDebouncedNameInputs } from './utils'+import {+ cohortPercentagesAddUp,+ normalizeCohortPercentages,+ parseCohortPercentage,+ useDebouncedNameInputs,+} from './utils'++// Print enough precision that the two figures in the imbalance warning cannot contradict each other:+// rounding a 99.996% total to hundredths would claim it adds up to 100% with 0% left over. Number()+// then drops the zeros toFixed pads with, and clears float noise like 0.0040000000000048.+const formatPercentage = (value: number): string => Number(value.toFixed(10)).toString()export function StepRandomCohortBranchConfiguration({node,@@ -77,25 +87,41 @@ export function StepRandomCohortBranchConfiguration({setWorkflowActionEdges(action.id, [...newBranchEdges, ...nonBranchEdges])}- const updateCohortPercentage = (index: number, percentage: number): void => {+ // While a percentage field is focused it displays the raw text being typed, keyed by cohort index.+ // Feeding the parsed number straight back as the input's value would drop a trailing decimal+ // point, so a fractional share could never be typed: "3." parses to 3 and the field re-renders+ // without the dot, leaving "3.3" unreachable.+ const [percentageDrafts, setPercentageDrafts] = useState<Record<number, string>>({})++ const updateCohortPercentage = (index: number, value: string): void => {+ setPercentageDrafts((drafts) => ({ ...drafts, [index]: value }))+ const percentage = parseCohortPercentage(value)setCohorts(cohorts.map((cohort, i) => (i === index ? { ...cohort, percentage } : cohort)))}+ const clearPercentageDraft = (index: number): void => {+ setPercentageDrafts((drafts) => {+ const remaining = { ...drafts }+ delete remaining[index]+ return remaining+ })+ }+const normalizePercentages = (): void => {- const count = cohorts.length- if (count === 0) {+ if (cohorts.length === 0) {return}- const base = Math.floor(100 / count)- const remainder = 100 - base * count- const normalized = cohorts.map((cohort, i) => {- // Distribute remainder to the first cohorts- return { ...cohort, percentage: base + (i < remainder ? 1 : 0) }- })- setCohorts(normalized)+ const normalized = normalizeCohortPercentages(cohorts.length)+ setCohorts(cohorts.map((cohort, i) => ({ ...cohort, percentage: normalized[i] })))+ // Every share is replaced, so any draft still open is stale text sitting over a new value. The+ // button cannot be relied on to blur the field first: Safari leaves focus where it was.+ setPercentageDrafts({})}- const totalPercentage = cohorts.reduce((sum, cohort) => sum + cohort.percentage, 0)+ const percentages = cohorts.map((cohort) => cohort.percentage)+ const totalPercentage = percentages.reduce((sum, percentage) => sum + percentage, 0)+ const isBalanced = cohortPercentagesAddUp(percentages)+ const shortfall = 100 - totalPercentagereturn (<>@@ -120,8 +146,10 @@ export function StepRandomCohortBranchConfiguration({type="number"min="0"max="100"- value={cohort.percentage}- onChange={(e) => updateCohortPercentage(index, parseInt(e.target.value) || 0)}+ step="any"+ value={percentageDrafts[index] ?? String(cohort.percentage)}+ onChange={(e) => updateCohortPercentage(index, e.target.value)}+ onBlur={() => clearPercentageDraft(index)}className="w-20 px-2 py-1 border rounded"/><span>%</span>@@ -129,15 +157,19 @@ export function StepRandomCohortBranchConfiguration({</div>))}- {totalPercentage !== 100 && (- <div className="text-sm text-orange-600">Total percentage: {totalPercentage}% (should equal 100%)</div>+ {cohorts.length > 0 && !isBalanced && (+ <div className="text-sm text-orange-600">+ {shortfall > 0+ ? `These add up to ${formatPercentage(totalPercentage)}%. The remaining ${formatPercentage(shortfall)}% will go to the last cohort.`+ : `These add up to ${formatPercentage(totalPercentage)}%. Later cohorts will get less than their share, and some may never be used.`}+ </div>)}<div className="flex gap-2"><LemonButton type="secondary" icon={<IconPlus />} onClick={() => addCohort()} className="flex-1">Add cohort</LemonButton>- <LemonButton type="secondary" onClick={normalizePercentages} tooltip="Normalize cohort percentages">+ <LemonButton type="secondary" onClick={normalizePercentages} tooltip="Split evenly across all cohorts"><IconBalance /></LemonButton></div>diff --git a/products/workflows/frontend/Workflows/hogflows/steps/utils.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/utils.test.tsindex 01cc1e1b467a..ba7edaae6469 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/utils.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/utils.test.ts@@ -1,5 +1,8 @@import {+ cohortPercentagesAddUp,getBranchRemovalDisabledReason,+ normalizeCohortPercentages,+ parseCohortPercentage,removeBranchEdge,updateItemWithOptionalName,updateOptionalName,@@ -216,6 +219,79 @@ describe('utils', () => {})})+ describe('normalizeCohortPercentages', () => {+ it.each([+ { name: 'splits evenly when the count divides 100', count: 4, expected: [25, 25, 25, 25] },+ {+ name: 'uses a fractional share when whole percents cannot divide 100',+ count: 8,+ expected: [12.5, 12.5, 12.5, 12.5, 12.5, 12.5, 12.5, 12.5],+ },+ {+ name: 'spreads the leftover hundredths across the leading cohorts',+ count: 3,+ expected: [33.34, 33.33, 33.33],+ },+ { name: 'returns nothing when there are no cohorts', count: 0, expected: [] },+ ])('$name', ({ count, expected }) => {+ expect(normalizeCohortPercentages(count)).toEqual(expected)+ })++ // Allocating in whole percents summed to 100 too, but unevenly: 30 cohorts came out as ten+ // shares of 4% and twenty of 3%, so a third of the branches took 33% more traffic than the+ // rest. Asserting the total alone would not have caught that, hence the per-share bound.+ it.each([2, 3, 7, 8, 30, 99])('gives %i cohorts an equal share totalling 100', (count) => {+ const percentages = normalizeCohortPercentages(count)+ const total = percentages.reduce((sum, percentage) => sum + percentage, 0)++ expect(percentages).toHaveLength(count)+ expect(total).toBeCloseTo(100, 6)+ for (const percentage of percentages) {+ expect(Math.abs(percentage - 100 / count)).toBeLessThanOrEqual(0.01)+ }+ })+ })++ describe('cohortPercentagesAddUp', () => {+ // Both directions of this have bitten: comparing against 100 exactly reports the balance+ // button's own output as unbalanced, while a tolerance wide enough to cover a hundredth of a+ // percent hides shortfalls the runtime really does reroute to the last cohort.+ it.each([2, 3, 7, 8, 30, 99])('accepts the even split produced for %i cohorts', (count) => {+ expect(cohortPercentagesAddUp(normalizeCohortPercentages(count))).toBe(true)+ })++ it.each([+ { name: 'accepts shares totalling exactly 100', percentages: [50, 50], expected: true },+ {+ name: 'rejects a shortfall smaller than a hundredth of a percent',+ percentages: [50, 49.996],+ expected: false,+ },+ { name: 'rejects a whole-percent shortfall', percentages: [30, 30, 30], expected: false },+ { name: 'rejects an excess', percentages: [60, 60], expected: false },+ { name: 'rejects no shares at all', percentages: [], expected: false },+ ])('$name', ({ percentages, expected }) => {+ expect(cohortPercentagesAddUp(percentages)).toBe(expected)+ })+ })++ describe('parseCohortPercentage', () => {+ // A number field accepts more than plain decimals, and its max attribute only gates form+ // validation, which this input is not wired to. Without the clamp, "1e5" stores 100000 and+ // every cohort after the first becomes unreachable.+ it.each([+ { name: 'keeps a fractional share', value: '3.3', expected: 3.3 },+ { name: 'keeps a whole share', value: '50', expected: 50 },+ { name: 'clamps scientific notation over the maximum', value: '1e5', expected: 100 },+ { name: 'clamps a value over the maximum', value: '500', expected: 100 },+ { name: 'clamps a negative value up to zero', value: '-5', expected: 0 },+ { name: 'reads empty text as zero', value: '', expected: 0 },+ { name: 'reads unparseable text as zero', value: 'abc', expected: 0 },+ ])('$name', ({ value, expected }) => {+ expect(parseCohortPercentage(value)).toBe(expected)+ })+ })+describe('updateItemWithOptionalName', () => {it('should update name at specified index', () => {const items = [diff --git a/products/workflows/frontend/Workflows/hogflows/steps/utils.ts b/products/workflows/frontend/Workflows/hogflows/steps/utils.tsindex 3a1efb1ea7d9..d2d773fac7ef 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/utils.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/utils.ts@@ -30,6 +30,54 @@ export function removeBranchEdge(branchEdges: HogFlowEdge[], conditionIndex: numreturn branchEdges.filter((e) => e.index !== conditionIndex).map((edge, i) => ({ ...edge, index: i }))}+/**+ * Percentages for an even N-way cohort split, summing to exactly 100.+ *+ * Shares are allocated in hundredths of a percent rather than whole percents, because whole percents+ * can't divide 100 evenly for most counts and the runtime routes any shortfall to the last cohort+ * (see getRandomCohort). Allocating in whole percents therefore gave 30 cohorts ten shares of 4% and+ * twenty of 3%, so a third of the branches carried 33% more than the rest. The leftover hundredths+ * are spread one each across the leading cohorts, which keeps every share within 0.01 of its fair+ * value.+ */+export function normalizeCohortPercentages(count: number): number[] {+ if (count <= 0) {+ return []+ }+ const hundredthsPerPercent = 100+ const totalHundredths = 100 * hundredthsPerPercent+ const base = Math.floor(totalHundredths / count)+ const leftover = totalHundredths - base * count+ return Array.from({ length: count }, (_, i) => (base + (i < leftover ? 1 : 0)) / hundredthsPerPercent)+}++// Adding floats accumulates error, so a set of shares that ought to total 100 can land a hair off (an+// even thirty-way split sums to 99.99999999999997). Anything under this counts as that noise. The+// bound is three orders of magnitude above the worst error an even split accumulates at any workable+// branch count, and far below a difference anyone would type, so a real imbalance still registers.+const FLOAT_SUM_TOLERANCE = 1e-9++/** Whether a set of cohort shares adds up to a whole 100%, ignoring float summing error. */+export function cohortPercentagesAddUp(percentages: number[]): boolean {+ const total = percentages.reduce((sum, percentage) => sum + percentage, 0)+ return Math.abs(total - 100) < FLOAT_SUM_TOLERANCE+}++/**+ * Read a percentage field's raw text into the value to store, clamped to the 0-100 the field declares.+ *+ * The clamp is load-bearing: min/max on a number input only gate form validation, which this field is+ * not wired to, so without it any out-of-range text a browser accepts as a number gets persisted.+ * Scientific notation is the easy one to miss, since "1e5" is valid input to a number field.+ */+export function parseCohortPercentage(value: string): number {+ const parsed = Number.parseFloat(value)+ if (!Number.isFinite(parsed)) {+ return 0+ }+ return Math.min(100, Math.max(0, parsed))+}+export function updateOptionalName<T>(obj: T & { name?: string }, name: string | undefined): T & { name?: string } {const updated = { ...obj }if (name) {