: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(experiments): give every watch card its own recordings (#83112)
Marcel Poelker58332324f152
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsxindex f6583affdf0e..c2a7a6c05565 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx@@ -24,6 +24,7 @@ import {type ExperimentWatchCardApi,} from 'products/experiments/frontend/generated/api.schemas'+import { hasEnded } from '../experimentStatus'import { type ExperimentReplayRecording, experimentReplayTabLogic } from './experimentReplayTabLogic'import { VariantTag } from './VariantTag'@@ -59,6 +60,16 @@ function cardSentence(card: ExperimentWatchCardApi, armKeys: string[]): string {return `${STRENGTH_WORD[card.strength ?? ExperimentWatchCardStrengthEnumApi.More]} than in ${others}`}+/**+ * How many recordings a card can show, written the way it has to be read. A count that reached the+ * ceiling is a floor, and a bare number beside an event name reads as how often that event+ * happened, which the Results tab answers over a different window and unit. Saturated counts are+ * also the ones that look equal across variants when the underlying event isn't.+ */+function recordingCount(card: ExperimentWatchCardApi, maxRecordings: number): string {+ return card.recording_count >= maxRecordings ? `${maxRecordings}+` : `${card.recording_count}`+}+/*** A comparison card whose event one of the experiment's metrics counts. The tag is what stops the* card being read as a second answer about that metric: the results measure the same event over the@@ -80,11 +91,13 @@ function WatchCard({card,selected,armKeys,+ maxRecordings,onSelect,}: {card: ExperimentWatchCardApiselected: booleanarmKeys: string[]+ maxRecordings: numberonSelect: (card: ExperimentWatchCardApi | null) => void}): JSX.Element {return (@@ -105,7 +118,10 @@ function WatchCard({{/* Pushed to the bottom rather than following the text, so the footers line upacross a row whose cards carry different numbers of lines. */}<div className="mt-auto flex w-full items-center justify-between pt-2 text-xs">- <span className="text-secondary">{pluralize(card.recording_count, 'recording')}</span>+ <span className="text-secondary">+ {recordingCount(card, maxRecordings)}{' '}+ {pluralize(card.recording_count, 'recording', undefined, false)}+ </span><span className="font-medium">{selected ? 'Showing below' : 'Watch'}</span></div></button>@@ -123,12 +139,14 @@ function MetricEventCard({metricName,cards,selectedCard,+ maxRecordings,onSelect,}: {event: stringmetricName: string | nullcards: ExperimentWatchCardApi[]selectedCard: ExperimentWatchCardApi | null+ maxRecordings: numberonSelect: (card: ExperimentWatchCardApi | null) => void}): JSX.Element {return (@@ -149,7 +167,12 @@ function MetricEventCard({active={selected}aria-pressed={selected}onClick={() => onSelect(selected ? null : card)}- tooltip={`${pluralize(card.recording_count, 'recording')} in ${card.variant}`}+ tooltip={`${recordingCount(card, maxRecordings)} ${pluralize(+ card.recording_count,+ 'recording',+ undefined,+ false+ )} in ${card.variant}`}data-attr="experiment-watch-metric-variant"><span className="flex items-center gap-1.5">@@ -157,7 +180,9 @@ function MetricEventCard({{/* The count stays on the chip's face rather than in thetooltip: without it two variants of the same event lookinterchangeable. */}- <span className="text-xs text-secondary">{card.recording_count}</span>+ <span className="text-xs text-secondary">+ {recordingCount(card, maxRecordings)}+ </span></span></LemonButton>)@@ -184,6 +209,7 @@ function ShelfFrame({cards,selectedCard,recordingsById,+ maxRecordings,onOpenHighlight,children,}: {@@ -192,6 +218,7 @@ function ShelfFrame({cards: ExperimentWatchCardApi[]selectedCard: ExperimentWatchCardApi | nullrecordingsById: Map<string, ExperimentReplayRecording>+ maxRecordings: numberonOpenHighlight: (card: ExperimentWatchCardApi, sessionId: string, position: number) => voidchildren: React.ReactNode}): JSX.Element {@@ -207,7 +234,12 @@ function ShelfFrame({</div>{children}{selectedHere && (- <HighlightList card={selectedHere} recordingsById={recordingsById} onOpenHighlight={onOpenHighlight} />+ <HighlightList+ card={selectedHere}+ recordingsById={recordingsById}+ maxRecordings={maxRecordings}+ onOpenHighlight={onOpenHighlight}+ />)}</div>)@@ -219,6 +251,7 @@ function Shelf({cards,selectedCard,armKeys,+ maxRecordings,onSelect,recordingsById,onOpenHighlight,@@ -228,6 +261,7 @@ function Shelf({cards: ExperimentWatchCardApi[]selectedCard: ExperimentWatchCardApi | nullarmKeys: string[]+ maxRecordings: numberonSelect: (card: ExperimentWatchCardApi | null) => voidrecordingsById: Map<string, ExperimentReplayRecording>onOpenHighlight: (card: ExperimentWatchCardApi, sessionId: string, position: number) => void@@ -242,6 +276,7 @@ function Shelf({cards={cards}selectedCard={selectedCard}recordingsById={recordingsById}+ maxRecordings={maxRecordings}onOpenHighlight={onOpenHighlight}><div className="flex flex-wrap gap-2">@@ -251,6 +286,7 @@ function Shelf({card={card}selected={isSameCard(selectedCard, card)}armKeys={armKeys}+ maxRecordings={maxRecordings}onSelect={onSelect}/>))}@@ -272,10 +308,12 @@ function Shelf({function HighlightList({card,recordingsById,+ maxRecordings,onOpenHighlight,}: {card: ExperimentWatchCardApirecordingsById: Map<string, ExperimentReplayRecording>+ maxRecordings: numberonOpenHighlight: (card: ExperimentWatchCardApi, sessionId: string, position: number) => void}): JSX.Element {if (card.highlights.length === 0) {@@ -293,8 +331,8 @@ function HighlightList({<div className="flex flex-col gap-1" data-attr="experiment-watch-highlights"><div className="flex items-baseline gap-2"><span className="text-xs text-muted">- {pluralize(card.highlights.length, 'recording')} to start with, out of the {card.recording_count}{' '}- behind {card.event}:+ {pluralize(card.highlights.length, 'recording')} to start with, out of the{' '}+ {recordingCount(card, maxRecordings)} behind {card.event}:</span></div><div className="flex w-fit max-w-full flex-col overflow-hidden rounded border border-primary">@@ -398,6 +436,10 @@ export function ExperimentBehaviorComparison({) : (<WatchShelvesdeltas={sessionEventDeltas}+ // What "no differences yet" is allowed to promise. Read from the status rather+ // than from end_date, so a state that carries an end date without having+ // stopped enrolling people cannot reach the past-tense copy.+ ended={hasEnded(experiment)}selectedCard={selectedWatchCard}onSelect={selectWatchCard}recordingsById={loadedRecordingsById}@@ -417,12 +459,14 @@ export function ExperimentBehaviorComparison({function WatchShelves({deltas,+ ended,selectedCard,onSelect,recordingsById,onOpenHighlight,}: {deltas: ExperimentSessionEventDeltaResponseApi+ ended: booleanselectedCard: ExperimentWatchCardApi | nullonSelect: (card: ExperimentWatchCardApi | null) => voidrecordingsById: Map<string, ExperimentReplayRecording>@@ -457,8 +501,9 @@ function WatchShelves({broken instead. */}{behaviorCards.length === 0 && frictionCards.length === 0 && (<div className="text-xs text-secondary">- No variant shows clearly different behavior in its recorded sessions yet. Differences small enough- to be chance don't get a card, so this can change as more people are exposed.+ {ended+ ? "No variant showed clearly different behavior in its recorded sessions. Differences small enough to be chance don't get a card."+ : "No variant shows clearly different behavior in its recorded sessions yet. Differences small enough to be chance don't get a card, so this can change as more people are exposed."}</div>)}<Shelf@@ -466,6 +511,7 @@ function WatchShelves({cards={behaviorCards}selectedCard={selectedCard}armKeys={armKeys}+ maxRecordings={deltas.max_card_recordings}onSelect={onSelect}recordingsById={recordingsById}onOpenHighlight={onOpenHighlight}@@ -475,6 +521,7 @@ function WatchShelves({cards={frictionCards}selectedCard={selectedCard}armKeys={armKeys}+ maxRecordings={deltas.max_card_recordings}onSelect={onSelect}recordingsById={recordingsById}onOpenHighlight={onOpenHighlight}@@ -485,6 +532,7 @@ function WatchShelves({cards={variantOnlyCards}selectedCard={selectedCard}armKeys={armKeys}+ maxRecordings={deltas.max_card_recordings}onSelect={onSelect}recordingsById={recordingsById}onOpenHighlight={onOpenHighlight}@@ -496,6 +544,7 @@ function WatchShelves({cards={metricCards}selectedCard={selectedCard}recordingsById={recordingsById}+ maxRecordings={deltas.max_card_recordings}onOpenHighlight={onOpenHighlight}><div className="flex flex-wrap gap-2">@@ -508,6 +557,7 @@ function WatchShelves({metricName={cards[0].metric_name}cards={cards}selectedCard={selectedCard}+ maxRecordings={deltas.max_card_recordings}onSelect={onSelect}/>)diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.tsindex 38ebbf7b9f08..48645881f3aa 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts@@ -70,6 +70,7 @@ const DELTA_RESPONSE = {sessions_truncated: false,events_truncated: false,min_arm_persons: 50,+ max_card_recordings: 20,too_early: false,}diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 89ad8f565efd..11fecf0b57c0 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1944,9 +1944,11 @@ class ExperimentWatchCardSerializer(serializers.Serializer):)recording_count = serializers.IntegerField(help_text=(- f"How many recordings the card carries, at most {MAX_CARD_RECORDINGS}. Every card is backed by "- "recordings that actually exist: a finding whose sessions were never recorded is dropped rather "- "than promised."+ f"How many recordings the card carries, at most max_card_recordings ({MAX_CARD_RECORDINGS}). Every "+ "card is backed by recordings that actually exist: a finding whose sessions were never recorded is "+ "dropped rather than promised. A count sitting on the ceiling means at least that many, so say 'at "+ "least' and never compare two such counts: how often the event happened is the experiment's results, "+ "and this only counts what replay kept."))session_ids = serializers.ListField(@@ -2077,6 +2079,12 @@ class ExperimentSessionEventDeltaResponseSerializer(serializers.Serializer):"cards would be noise whatever the evidence bar allows."))+ max_card_recordings = serializers.IntegerField(+ help_text=(+ "The most recordings one card can carry. A card whose recording_count equals this hit the ceiling, "+ "so report it as 'at least this many' rather than as a count."+ )+ )too_early = serializers.BooleanField(help_text=("True when fewer than two variants have min_arm_persons exposed people, so no comparison exists and "diff --git a/products/experiments/backend/session_event_deltas.py b/products/experiments/backend/session_event_deltas.pyindex cf4cac745d1a..d531522ac0a4 100644--- a/products/experiments/backend/session_event_deltas.py+++ b/products/experiments/backend/session_event_deltas.py@@ -155,6 +155,13 @@ MAX_METRIC_CARD_EVENTS = 2# How many recordings a card names to start with. Enough to offer a choice, few enough that the# reader still opens one instead of reading a second list.MAX_CARD_HIGHLIGHTS = 3+# Two cards sharing this much of their recordings are one playlist under two names, so the second+# one is dropped, e.g. if two cards share 18 of their 20 recordings.+DUPLICATE_CARD_OVERLAP = 0.8+# How far one count can carry a recording up the highlight order. Past a few occurrences a count+# measures how long the session is rather than what it shows, and raw totals hand every card the+# same longest session. Only the ranking is bounded; the reason still prints the true count.+HIGHLIGHT_COUNT_DAMPING = 3# Recording candidates fetched per card before replay existence is checked, and how many survive# onto the card. The margin absorbs sessions that were never recorded without a second round trip.MAX_CARD_RECORDING_CANDIDATES = 60@@ -384,6 +391,10 @@ class ExperimentWatchResult:sessions_truncated: boolevents_truncated: boolmin_arm_persons: int+ # Reported so a reader can tell a card carrying every recording of its event from one that ran+ # into the ceiling. A count sitting on the cap is a floor, and printed as a plain number beside+ # an event name it reads as a measurement of that event.+ max_card_recordings: inttoo_early: bool@@ -394,15 +405,21 @@ def all_card_session_ids(result: ExperimentWatchResult) -> list[str]:def finalize_watch_cards(result: ExperimentWatchResult, accessible_session_ids: list[str]) -> ExperimentWatchResult:- """Cut every card down to the recordings this viewer may open, dropping the ones left with none.+ """The shelf this viewer gets: their recordings, no card restating another, highlights assigned.Applied on read rather than inside the scan, for the same reason the session buckets do it: the- shelf is cached — and shared across viewers with the same property restrictions — so this cut- is what keeps one viewer's entry from leaking another's denied recordings, and it honors a+ shelf is cached, and shared across viewers with the same property restrictions, so this cut is+ what keeps one viewer's entry from leaking another's denied recordings, and it honors arevocation that lands while an entry is still warm. A card that loses every recording is- dropped rather than shown greyed-out — the same rule the scan applies to sessions replay never+ dropped rather than shown greyed-out, the same rule the scan applies to sessions replay neverrecorded, since either way there is nothing to watch behind it. `recording_count` is recomputedso it keeps meaning "recordings this card can show you".++ The duplicate cut and the highlight assignment run here rather than in the scan because both+ are statements about the shelf a viewer sees. Cutting a duplicate against recordings this+ viewer can't open would drop a card whose remaining recordings they can, and could leave two+ surviving cards showing the same ones; naming a card's first recordings before either cut lets+ a card that is no longer on the shelf keep its claim on one."""accessible = set(accessible_session_ids)cards = []@@ -413,7 +430,7 @@ def finalize_watch_cards(result: ExperimentWatchResult, accessible_session_ids:cards.append(replace(card, recording_count=len(session_ids), session_ids=session_ids, highlights=highlights))- return replace(result, cards=cards)+ return replace(result, cards=_assign_highlights(_drop_duplicate_recording_sets(cards)))def get_experiment_session_event_deltas(team: Team, user: User, experiment: Experiment) -> ExperimentWatchResult:@@ -580,6 +597,7 @@ def get_experiment_session_event_deltas(team: Team, user: User, experiment: Expesessions_truncated=scan.sessions_truncated,events_truncated=scan.events_truncated,min_arm_persons=MIN_ARM_PERSONS,+ max_card_recordings=MAX_CARD_RECORDINGS,too_early=too_early,)safe_cache_set(cache_key, result, timeout=DELTA_CACHE_TTL)@@ -723,7 +741,7 @@ def _cache_key(# applied on read. One viewer's scan then serves every viewer whose restrictions match, which# on the heaviest read in this family is the difference between paying it once per team per# TTL and once per viewer.- return f"experiment_session_event_deltas_v6_{team.pk}_{experiment.pk}_{digest}"+ return f"experiment_session_event_deltas_v7_{team.pk}_{experiment.pk}_{digest}"def _metric_event_names(metrics: list[MetricEventSource]) -> set[str]:@@ -1102,6 +1120,63 @@ def _pick_behavior_cards()+def _shares_recordings(session_ids: set[str], other: set[str]) -> bool:+ """Whether one card's recordings are, near enough, already the other's.++ Measured against the smaller card rather than the union, so a card whose recordings all sit+ inside a longer one counts as a duplicate too.+ """+ return len(session_ids & other) >= min(len(session_ids), len(other)) * DUPLICATE_CARD_OVERLAP+++def _drop_duplicate_recording_sets(cards: list[ExperimentWatchCard]) -> list[ExperimentWatchCard]:+ """The shelf with every card that only restates a higher-ranked card's recordings taken out.++ Two events an arm's people do together are ranked as two findings, because the comparison reads+ one event name at a time and both separate the arms. The reader gets one playlist twice, and on+ a redesign experiment, where a whole flow's events move together, that is most of the shelf.++ Compared within a shelf and never across them. An event a variant renders itself always+ co-occurs with the behavior it drives, so cutting the variant's-own-rendering card against the+ behavior card would empty the shelf built to hold it, and a metric shortcut is an offer to+ watch a metric event happen rather than a restatement of the finding it shares recordings with.++ Cards arrive in rank order, so the one kept is the one that earned its place. A dropped card is+ not replaced by the next-ranked candidate: candidates are capped before their recordings are+ resolved, and refilling would cost another round trip to find out whether the replacement can+ be backed by a recording at all.+ """+ kept: list[ExperimentWatchCard] = []+ seen_by_kind: dict[WatchCardKind, list[set[str]]] = {}+ for card in cards:+ session_ids = set(card.session_ids)+ shelf = seen_by_kind.setdefault(card.kind, [])+ if any(_shares_recordings(session_ids, other) for other in shelf):+ continue+ shelf.append(session_ids)+ kept.append(card)+ return kept+++def _assign_highlights(cards: list[ExperimentWatchCard]) -> list[ExperimentWatchCard]:+ """Each card cut down to the few recordings it names first, taken from its own ranking.++ The shelf's cards overlap by construction, so a recording an earlier card already names sorts+ last here rather than being dropped: no card is left without highlights, and no reader is sent+ to the same recording from every card on the shelf. Cards arrive in rank order, so the stronger+ card gets first claim on a recording both could name.+ """+ claimed: set[str] = set()+ assigned = []+ for card in cards:+ unclaimed = [highlight for highlight in card.highlights if highlight.session_id not in claimed]+ already = [highlight for highlight in card.highlights if highlight.session_id in claimed]+ highlights = (unclaimed + already)[:MAX_CARD_HIGHLIGHTS]+ claimed.update(highlight.session_id for highlight in highlights)+ assigned.append(replace(card, highlights=highlights))+ return assigned++def _metric_events_by_name(metrics: list[MetricEventSource], experiment: Experiment) -> tuple[list[_MetricEvent], dict[str, list[EventsNode]]]:@@ -1445,9 +1520,15 @@ def _recordings_for_cards(continuefound[pair] = _CardRecordings(session_ids=[recording.session_id for recording in kept],- # On a card whose own event is one of the friction signals, the signal count already is- # the repetition, so counting both would say "2 rage clicks, did this 2 times".- highlights=_pick_highlights(kept, count_repetition=pair[0] not in FRICTION_EVENTS),+ # Ranked, but not yet cut to the few a card names: which of them this card ends up+ # naming depends on the cards beside it, and which cards those are is settled per+ # viewer.+ highlights=_rank_highlights(+ kept,+ # On a card whose own event is one of the friction signals, the signal count already+ # is the repetition, so counting both would say "2 rage clicks, did this 2 times".+ count_repetition=pair[0] not in FRICTION_EVENTS,+ ),)return found@@ -1465,10 +1546,13 @@ def _repetition_alias(index: int) -> str:return f"repetition_{index}"-def _pick_highlights(+def _rank_highlights(recordings: list[_CandidateRecording], *, count_repetition: bool) -> list[ExperimentWatchHighlight]:- """Which of a card's recordings to open first, and everything each of them carries.+ """A card's recordings worth opening first, best first, each with everything it carries.++ Every recording that carries anything, rather than only the few a card shows: which of them+ this card names is decided in `_assign_highlights`, once the shelf beside it is final.Ranked on the friction a session shows as a whole rather than by naming the leader of eachsignal in turn. Per-signal leaders describe half of what they point at and hide the sessions@@ -1478,16 +1562,18 @@ def _pick_highlights(showing a person hitting two problems in a row, which is the case this surface exists to find.Kinds before volume for the same reason: a session that rage clicked and then hit an error says- more about the variant than one that only rage clicked twice as often.+ more about the variant than one that only rage clicked twice as often. Volume then decides the+ ties, but damped, because past a few occurrences a count measures the session's length, and+ ranking on raw totals puts the longest session first on every card it appears on.Repeating the card's own event counts as one more kind of signal, from two occurrences up- since one is what put the session on the card at all. It ranks below friction on a tie by- sitting last in the reason, but it is what gives a card without any friction a highlight- worth the name: on a behavior card, "did this five times" is the session where the difference- the card claims is most on screen. `count_repetition` is False when the card's own event is a- friction signal, whose count already says the same thing.+ since one is what put the session on the card at all, and it outranks friction volume on a tie:+ on a behavior card the recording worth opening first is the one where the difference the card+ claims is most on screen, not the one carrying the most of something every card shows.+ `count_repetition` is False when the card's own event is a friction signal, whose count already+ says the same thing."""- scored: list[tuple[int, int, str, str]] = []+ scored: list[tuple[int, int, int, str, str]] = []for recording in recordings:present = [(recording.signals[event], singular)@@ -1503,12 +1589,13 @@ def _pick_highlights(if not phrases:continuekinds = len(present) + (1 if repetition > 1 else 0)- total = sum(count for count, _singular in present) + (repetition if repetition > 1 else 0)- scored.append((kinds, total, recording.session_id, ", ".join(phrases)))+ damped_repetition = min(repetition, HIGHLIGHT_COUNT_DAMPING) if repetition > 1 else 0+ damped_signals = sum(min(count, HIGHLIGHT_COUNT_DAMPING) for count, _singular in present)+ scored.append((kinds, damped_repetition, damped_signals, recording.session_id, ", ".join(phrases)))# Ties broken on the session id rather than left to dict order, so the same shelf computed# twice names the same recordings.- scored.sort(key=lambda entry: (-entry[0], -entry[1], entry[2]))+ scored.sort(key=lambda entry: (-entry[0], -entry[1], -entry[2], entry[3]))return [ExperimentWatchHighlight(session_id=session_id, reason=reason)- for _kinds, _total, session_id, reason in scored[:MAX_CARD_HIGHLIGHTS]+ for _kinds, _repetition, _signals, session_id, reason in scored]diff --git a/products/experiments/backend/test/test_session_event_deltas_api.py b/products/experiments/backend/test/test_session_event_deltas_api.pyindex 451813e6ef27..575046811dc3 100644--- a/products/experiments/backend/test/test_session_event_deltas_api.py+++ b/products/experiments/backend/test/test_session_event_deltas_api.py@@ -454,6 +454,31 @@ class TestExperimentSessionEventDeltas(ClickhouseTestMixin, APILicensedTest):]assert [(card["event"], card["variant"]) for card in self._cards(data, "behavior")] == [("pricing_faq", "test")]+ @rank_anything+ def test_a_card_showing_another_cards_recordings_is_left_off_the_shelf(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ self._arm("control", [["purchase"], ["purchase"], ["faq_expanded", "purchase"], ["checkout_start", "purchase"]])+ # `faq_expanded` happens in exactly the sessions `pricing_faq` does, so its card is a second+ # name for one playlist: a reader who clicks it is shown what the card above already gave+ # them, which reads as the shelf being broken rather than as two findings.+ self._arm("test", [["pricing_faq", "faq_expanded", "purchase"]] * 4 + [["checkout_start", "purchase"]] * 4)+ flush_persons_and_events()++ data = self._post_deltas(experiment).json()++ # The weaker of the twins goes; `checkout_start` sits on recordings of its own and stays.+ assert [(card["event"], card["variant"]) for card in self._cards(data, "behavior")] == [+ ("pricing_faq", "test"),+ ("checkout_start", "test"),+ ]+ # The shortcut's recordings are the pricing_faq card's four and four more, but the two+ # shelves say different things about them: one is a finding, the other only offers to show+ # a metric event happening. Cutting one against the other would delete that distinction.+ assert [(card["event"], card["variant"]) for card in self._cards(data, "metric")] == [+ ("purchase", "control"),+ ("purchase", "test"),+ ]+@rank_anythingdef test_a_cards_highlights_name_which_of_its_recordings_to_open_first(self) -> None:experiment = self._create_experiment(metrics=[PURCHASE_METRIC])@@ -481,6 +506,62 @@ class TestExperimentSessionEventDeltas(ClickhouseTestMixin, APILicensedTest):(most_rage, "2 rage clicks"),]+ @rank_anything+ def test_a_noisy_session_does_not_outrank_the_behavior_the_card_claims(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ self._arm("control", [[]] * 2)+ # Six errors against one is the session being longer rather than six times more worth+ # watching, and counting them raw is what puts the longest session at the top of every card+ # it happens to back.+ noisy = self._session(+ variants=["test"],+ events=["pricing_faq", "pricing_faq", "$rageclick", "$dead_click"] + ["$exception"] * 6,+ )+ # Same three kinds of friction, and the card's own event five times over: the recording+ # where what the card claims is actually on screen.+ on_point = self._session(+ variants=["test"],+ events=["pricing_faq"] * 5 + ["$rageclick", "$exception", "$dead_click"],+ )+ flush_persons_and_events()++ data = self._post_deltas(experiment).json()++ card = next(card for card in self._cards(data, "behavior") if card["event"] == "pricing_faq")+ # The reasons still print what each recording really carries; only the ordering stops+ # reading volume as importance.+ assert [(highlight["session_id"], highlight["reason"]) for highlight in card["highlights"]] == [+ (on_point, "1 rage click, 1 error, 1 dead click, did this 5 times"),+ (noisy, "1 rage click, 6 errors, 1 dead click, did this 2 times"),+ ]++ @rank_anything+ def test_the_same_recording_does_not_lead_every_card(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ # The control occurrence ranks checkout_start below pricing_faq, so the shared recording+ # goes to the higher-ranked card rather than to whichever event sorts first.+ self._arm("control", [["checkout_start"], []])+ shared = self._session(+ variants=["test"],+ events=["pricing_faq", "checkout_start", "$rageclick", "$exception", "$dead_click"],+ )+ faq_rage = self._session(variants=["test"], events=["pricing_faq", "$rageclick"])+ self._session(variants=["test"], events=["pricing_faq"])+ checkout_rage = self._session(variants=["test"], events=["checkout_start", "$rageclick"])+ self._session(variants=["test"], events=["checkout_start"])+ flush_persons_and_events()++ data = self._post_deltas(experiment).json()++ cards = {card["event"]: card for card in self._cards(data, "behavior")}+ assert [highlight["session_id"] for highlight in cards["pricing_faq"]["highlights"]] == [shared, faq_rage]+ # The next card leads with a recording of its own instead of sending the reader back to the+ # one they were already told to open, and still offers the shared one last.+ assert [highlight["session_id"] for highlight in cards["checkout_start"]["highlights"]] == [+ checkout_rage,+ shared,+ ]+@rank_anythingdef test_friction_events_land_on_their_own_shelf(self) -> None:experiment = self._create_experiment(metrics=[PURCHASE_METRIC])@@ -711,6 +792,69 @@ class TestExperimentSessionEventDeltas(ClickhouseTestMixin, APILicensedTest):assert card["session_ids"] == [allowed]assert card["recording_count"] == 1+ @rank_anything+ def test_a_card_the_viewer_can_still_watch_survives_its_duplicate_being_cut(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ self._arm("control", [[]] * 2)+ # The two events happen together in four sessions, enough for one card to be cut as the+ # other's playlist. Each event also has a session of its own.+ shared = [self._session(variants=["test"], events=["pricing_faq", "faq_expanded"]) for _ in range(4)]+ faq_only = self._session(variants=["test"], events=["pricing_faq"])+ expanded_only = self._session(variants=["test"], events=["faq_expanded"])+ # Object-level controls can only target a recording that has a Postgres row.+ for session_id in shared:+ SessionRecording.objects.create(team=self.team, session_id=session_id)+ flush_persons_and_events()++ # This viewer may open neither card's shared recordings, which is what leaves the two cards+ # showing different recordings after all.+ with patch(+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object",+ side_effect=lambda obj, *args, **kwargs: getattr(obj, "session_id", None) not in shared,+ ):+ data = self._post_deltas(experiment).json()++ # Cutting duplicates before this viewer's own recordings are cut would drop the second card+ # over recordings they can't open, and leave the first with a single unrelated one.+ assert [(card["event"], card["session_ids"]) for card in self._cards(data, "behavior")] == [+ ("faq_expanded", [expanded_only]),+ ("pricing_faq", [faq_only]),+ ]++ @rank_anything+ def test_a_card_cut_as_a_duplicate_does_not_reserve_a_recording_for_itself(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ self._arm("control", [[]] * 2)+ # Both events happen in all four sessions, so one card is cut as the other's playlist. Every+ # session carries one rage click and nothing else, which leaves the highlight ranking on the+ # session id, and the staggered start times put those in the order they were created.+ together = [+ self._session(+ variants=["test"],+ events=["pricing_faq", "faq_expanded", "$rageclick"],+ at=EXPOSED_AT + timedelta(minutes=index),+ )+ for index in range(3)+ ]+ # The fourth carries a third event as well, and it is that event's card which should name it+ # first: the kept duplicate names the first three, so only the cut one ever wanted this.+ together.append(+ self._session(+ variants=["test"],+ events=["pricing_faq", "faq_expanded", "checkout_start", "$rageclick"],+ at=EXPOSED_AT + timedelta(minutes=3),+ )+ )+ self._session(variants=["test"], events=["checkout_start", "$rageclick"], at=EXPOSED_AT + timedelta(minutes=4))+ flush_persons_and_events()++ data = self._post_deltas(experiment).json()++ # The cut card would otherwise have claimed the fourth recording, having had the first three+ # taken by the card it duplicates, and pushed it down on the one card still showing it.+ checkout = next(card for card in self._cards(data, "behavior") if card["event"] == "checkout_start")+ assert checkout["highlights"][0]["session_id"] == together[3]+def test_requires_session_replay_access(self) -> None:experiment = self._create_experiment(metrics=[PURCHASE_METRIC])diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 7f543c50c901..17b4272e6073 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2327,7 +2327,7 @@ export interface ExperimentWatchCardApi {* @nullable*/metric_name: string | null- /** How many recordings the card carries, at most 20. Every card is backed by recordings that actually exist: a finding whose sessions were never recorded is dropped rather than promised. */+ /** How many recordings the card carries, at most max_card_recordings (20). Every card is backed by recordings that actually exist: a finding whose sessions were never recorded is dropped rather than promised. A count sitting on the ceiling means at least that many, so say 'at least' and never compare two such counts: how often the event happened is the experiment's results, and this only counts what replay kept. */recording_count: number/** The recordings themselves, most recent first, ready to hand to the recordings list as-is. */session_ids: string[]@@ -2394,6 +2394,8 @@ export interface ExperimentSessionEventDeltaResponseApi {events_truncated: boolean/** How many exposed people a variant needs before it can be compared at all. Below it a variant's cards would be noise whatever the evidence bar allows. */min_arm_persons: number+ /** The most recordings one card can carry. A card whose recording_count equals this hit the ceiling, so report it as 'at least this many' rather than as a count. */+ max_card_recordings: number/** True when fewer than two variants have min_arm_persons exposed people, so no comparison exists and cards is empty. Say 'too early to compare' and show the arms' counts; an empty shelf presented without this would read as 'the variants behaved identically'. */too_early: boolean}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ad84cac24fb5..8e98d3f16f2d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -31894,7 +31894,7 @@ export namespace Schemas {* @nullable*/metric_name: string | null;- /** How many recordings the card carries, at most 20. Every card is backed by recordings that actually exist: a finding whose sessions were never recorded is dropped rather than promised. */+ /** How many recordings the card carries, at most max_card_recordings (20). Every card is backed by recordings that actually exist: a finding whose sessions were never recorded is dropped rather than promised. A count sitting on the ceiling means at least that many, so say 'at least' and never compare two such counts: how often the event happened is the experiment's results, and this only counts what replay kept. */recording_count: number;/** The recordings themselves, most recent first, ready to hand to the recordings list as-is. */session_ids: string[];@@ -31961,6 +31961,8 @@ export namespace Schemas {events_truncated: boolean;/** How many exposed people a variant needs before it can be compared at all. Below it a variant's cards would be noise whatever the evidence bar allows. */min_arm_persons: number;+ /** The most recordings one card can carry. A card whose recording_count equals this hit the ceiling, so report it as 'at least this many' rather than as a count. */+ max_card_recordings: number;/** True when fewer than two variants have min_arm_persons exposed people, so no comparison exists and cards is empty. Say 'too early to compare' and show the arms' counts; an empty shelf presented without this would read as 'the variants behaved identically'. */too_early: boolean;}