Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): keep a running theme tally in the variant analysis scout (#114629)

Kim Svatos Dugan1004a8914236
diff --git a/products/replay_vision/backend/api/variants.py b/products/replay_vision/backend/api/variants.py
index ea43c44c3f20..fce31ac0ea02 100644
--- a/products/replay_vision/backend/api/variants.py
+++ b/products/replay_vision/backend/api/variants.py
@@ -49,6 +49,10 @@ class VariantAnalysisLineSerializer(serializers.Serializer):
count = serializers.IntegerField(
help_text="How many of this variant's summaries the analysis read show the theme, as the scout counted them."
)
+ read = serializers.IntegerField(
+ allow_null=True,
+ help_text="How many of this variant's summaries the theme was counted over, when that is fewer than the analysis read in total. Null when the theme was counted over every summary the analysis read.",
+ )
example_observation_ids = serializers.ListField(
child=serializers.UUIDField(),
help_text="Observations of this variant the scout cited for the theme. Ids it can't back are dropped.",
@@ -62,6 +66,10 @@ class VariantAnalysisDifferenceSerializer(serializers.Serializer):
child=serializers.IntegerField(),
help_text="Summaries the analysis read that show the theme, per variant key, as the scout counted them.",
)
+ read = serializers.DictField(
+ child=serializers.IntegerField(),
+ help_text="Per variant key, how many summaries the theme was counted over, for a theme counted over fewer summaries than the analysis read in total. Empty when it was counted over all of them.",
+ )
class VariantsAnalysisStateSerializer(serializers.Serializer):
diff --git a/products/replay_vision/backend/tests/test_experiment_variants.py b/products/replay_vision/backend/tests/test_experiment_variants.py
index 25b78da1eb98..a5277db430e5 100644
--- a/products/replay_vision/backend/tests/test_experiment_variants.py
+++ b/products/replay_vision/backend/tests/test_experiment_variants.py
@@ -115,6 +115,8 @@ class TestExperimentVariants(_VisionAPITestCase):
"theme": "Hesitates at checkout",
"statement": "Waits on the payment step.",
"count": 9,
+ # A denominator below its own count would show a share above 100%.
+ "read": 5,
"example_observation_ids": [str(control.id), str(test.id)],
}
],
@@ -123,6 +125,8 @@ class TestExperimentVariants(_VisionAPITestCase):
"theme": "Hesitates at checkout",
"statement": "Rarely waits.",
"count": 2,
+ # A theme counted from a later run carries its own, smaller denominator.
+ "read": 20,
"example_observation_ids": [str(uuid.uuid4()), "not-an-id"],
}
],
@@ -132,6 +136,7 @@ class TestExperimentVariants(_VisionAPITestCase):
"theme": "Hesitates at checkout",
"statement": "Control waits more.",
"counts": {"control": 9, "test": 2},
+ "read": {"test": 20},
}
],
}
@@ -158,10 +163,12 @@ class TestExperimentVariants(_VisionAPITestCase):
"theme": "Hesitates at checkout",
"statement": "Waits on the payment step.",
"count": 9,
+ "read": None,
"example_observation_ids": [str(control.id)],
}
]
assert by_key["test"]["digest"][0]["example_observation_ids"] == []
+ assert by_key["test"]["digest"][0]["read"] == 20
assert by_key["control"]["analysis_observations"] == 30
assert by_key["beta"]["digest"] == [] and by_key["beta"]["analysis_observations"] == 0
assert body["differences"] == payload["differences"]
diff --git a/products/replay_vision/backend/variant_analysis.py b/products/replay_vision/backend/variant_analysis.py
index ef5ce850e6d2..59dc96a239f6 100644
--- a/products/replay_vision/backend/variant_analysis.py
+++ b/products/replay_vision/backend/variant_analysis.py
@@ -55,7 +55,7 @@ VARIANT_ANALYSIS_SCHEMA: dict[str, Any] = {
},
"observations_read": {
**_COUNTS_BY_VARIANT,
- "description": "How many summaries you read per variant key: the denominator of every count below.",
+ "description": "How many summaries per variant key your counts rest on: the denominator of every count below.",
},
"variants": {
"type": "object",
@@ -85,7 +85,12 @@ VARIANT_ANALYSIS_SCHEMA: dict[str, Any] = {
"count": {
"type": "integer",
"minimum": 0,
- "description": "Summaries of this variant you read that show the theme.",
+ "description": "Summaries of this variant, out of `observations_read`, that show the theme.",
+ },
+ "read": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Set only for a theme counted over fewer summaries than `observations_read`, because counting started later: how many summaries of this variant it was counted over.",
},
"example_observation_ids": {
"type": "array",
@@ -102,6 +107,10 @@ VARIANT_ANALYSIS_SCHEMA: dict[str, Any] = {
"theme": {"type": "string", "minLength": 1, "maxLength": _THEME_CHARS},
"statement": {"type": "string", "minLength": 1, "maxLength": _STATEMENT_CHARS},
"counts": {**_COUNTS_BY_VARIANT, "description": "Summaries showing the theme, per variant key."},
+ "read": {
+ **_COUNTS_BY_VARIANT,
+ "description": "Set only for a theme counted over fewer summaries than `observations_read`: per variant key, how many summaries it was counted over.",
+ },
},
},
},
@@ -119,6 +128,8 @@ class VariantAnalysisLine:
theme: str
statement: str
count: int
+ # Set when the theme was counted over fewer summaries than the record's `observations_read`.
+ read: int | None
example_observation_ids: tuple[str, ...]
@@ -127,6 +138,7 @@ class VariantAnalysisDifference:
theme: str
statement: str
counts: dict[str, int]
+ read: dict[str, int]
@frozen
@@ -214,6 +226,11 @@ def _counts(raw: Any) -> dict[str, int]:
return {str(key): value for key, value in raw.items() if isinstance(value, int) and value >= 0}
+def _read(raw: Any, count: int) -> int | None:
+ # A denominator below its own count is a scout error, and showing it would print a share above 100%.
+ return raw if isinstance(raw, int) and raw >= count else None
+
+
def _lines(raw: Any, cited_variants: dict[str, str]) -> dict[str, tuple[VariantAnalysisLine, ...]]:
if not isinstance(raw, dict):
return {}
@@ -226,6 +243,7 @@ def _lines(raw: Any, cited_variants: dict[str, str]) -> dict[str, tuple[VariantA
theme=str(item["theme"])[:_THEME_CHARS],
statement=str(item["statement"])[:_STATEMENT_CHARS],
count=item["count"],
+ read=_read(item.get("read"), item["count"]),
example_observation_ids=tuple(
str(observation_id)
for observation_id in (item.get("example_observation_ids") or [])[:MAX_EXAMPLES_PER_LINE]
@@ -249,6 +267,11 @@ def _differences(raw: Any) -> tuple[VariantAnalysisDifference, ...]:
theme=str(item["theme"])[:_THEME_CHARS],
statement=str(item["statement"])[:_STATEMENT_CHARS],
counts=_counts(item.get("counts")),
+ read={
+ key: read
+ for key, read in _counts(item.get("read")).items()
+ if read >= _counts(item.get("counts")).get(key, 0)
+ },
)
for item in raw[:MAX_DIFFERENCES]
if isinstance(item, dict) and isinstance(item.get("theme"), str) and isinstance(item.get("statement"), str)
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 17b72388ef5e..d6346940adb2 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -2253,6 +2253,11 @@ export interface VariantAnalysisLineApi {
statement: string
/** How many of this variant's summaries the analysis read show the theme, as the scout counted them. */
count: number
+ /**
+ * How many of this variant's summaries the theme was counted over, when that is fewer than the analysis read in total. Null when the theme was counted over every summary the analysis read.
+ * @nullable
+ */
+ read: number | null
/** Observations of this variant the scout cited for the theme. Ids it can't back are dropped. */
example_observation_ids: string[]
}
@@ -2293,6 +2298,11 @@ export interface VariantReadoutApi {
*/
export type VariantAnalysisDifferenceApiCounts = { [key: string]: number }
+/**
+ * Per variant key, how many summaries the theme was counted over, for a theme counted over fewer summaries than the analysis read in total. Empty when it was counted over all of them.
+ */
+export type VariantAnalysisDifferenceApiRead = { [key: string]: number }
+
export interface VariantAnalysisDifferenceApi {
/** The theme the difference rests on. */
theme: string
@@ -2300,6 +2310,8 @@ export interface VariantAnalysisDifferenceApi {
statement: string
/** Summaries the analysis read that show the theme, per variant key, as the scout counted them. */
counts: VariantAnalysisDifferenceApiCounts
+ /** Per variant key, how many summaries the theme was counted over, for a theme counted over fewer summaries than the analysis read in total. Empty when it was counted over all of them. */
+ read: VariantAnalysisDifferenceApiRead
}
export interface VariantsAnalysisStateApi {
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index 7d3d7e505bd9..320cfaad26a8 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -780,12 +780,14 @@ const variantsReadout = (overrides: Partial<ExperimentVariantsReadoutApi> = {}):
theme: 'first-try-payment',
statement: 'Most people complete payment on the first try.',
count: 21,
+ read: null,
example_observation_ids: ['00000000-0000-0000-0000-0000000000c1'],
},
{
theme: 'summary-rereads',
statement: 'Some people scroll the order summary twice before they pay.',
count: 8,
+ read: null,
example_observation_ids: [],
},
],
@@ -818,12 +820,14 @@ const variantsReadout = (overrides: Partial<ExperimentVariantsReadoutApi> = {}):
theme: 'payment-method-pause',
statement: 'Many people pause at the payment method step before they select an option.',
count: 11,
+ read: null,
example_observation_ids: ['00000000-0000-0000-0000-0000000000t1'],
},
{
theme: 'promo-field',
statement: 'Several people open and close the promo code field without entering a code.',
count: 7,
+ read: null,
example_observation_ids: [],
},
],
@@ -843,11 +847,13 @@ const variantsReadout = (overrides: Partial<ExperimentVariantsReadoutApi> = {}):
theme: 'payment-method-pause',
statement: 'Pauses at the payment method step appear far more often in test.',
counts: { test: 11, control: 2 },
+ read: {},
},
{
theme: 'promo-field',
statement: 'Promo code interactions appear only in test.',
counts: { test: 7, control: 0 },
+ read: {},
},
],
unattributed_count: 6,
diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantCard.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantCard.tsx
index 412e8cf06b74..eac1dbce69b3 100644
--- a/products/replay_vision/frontend/replay_scanners/components/variants/VariantCard.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantCard.tsx
@@ -96,8 +96,8 @@ export function VariantCard({
<li key={line.theme} className="text-sm">
<span>{line.statement}</span>{' '}
<span className="text-muted">
- {variant.analysis_observations != null
- ? `(${line.count} of ${variant.analysis_observations})`
+ {(line.read ?? variant.analysis_observations) != null
+ ? `(${line.count} of ${line.read ?? variant.analysis_observations})`
: `(${line.count})`}
</span>
{line.example_observation_ids.length > 0 && (
diff --git a/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx b/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx
index d0689a10b97f..1543589d72c6 100644
--- a/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/variants/VariantDifferencesCard.tsx
@@ -129,7 +129,7 @@ export function VariantDifferencesCard({
<span className="text-muted">
{`(${Object.entries(difference.counts)
.map(([key, count]) => {
- const outOf = analysisCount(key)
+ const outOf = difference.read?.[key] ?? analysisCount(key)
return outOf != null ? `${key} ${count} of ${outOf}` : `${key} ${count}`
})
.join(', ')})`}
diff --git a/products/replay_vision/frontend/replay_scanners/scannerScout.ts b/products/replay_vision/frontend/replay_scanners/scannerScout.ts
index 934cc65ca96b..f7f7dc62c068 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerScout.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerScout.ts
@@ -413,19 +413,32 @@ function variantAnalysisTemplate(scannerId: string, scannerName: string): Scanne
cron: SCANNER_SCOUT_CRON,
body: buildScoutBody(scannerId, {
heading: 'Replay Vision variant analysis',
- role: 'You compare the variants of the experiment one Replay Vision experiment scanner watches. Read its session summaries variant by variant, name the behaviors they share, and report whether users in each variant behave differently. Many experiments change behavior too little to see in a few dozen sessions, so "no clear difference" is an acceptable and expected outcome, not a failed run.',
+ role: 'You compare the variants of the experiment one Replay Vision experiment scanner watches. Read its session summaries variant by variant, name the behaviors they share, and report whether users in each variant behave differently. You keep a running tally of those behaviors across runs, so each run reads only the summaries that are new and still judges the whole experiment. Many experiments change behavior too little to see in a few dozen sessions, so "no clear difference" is an acceptable and expected outcome, not a failed run.',
+ window: 'Your window is the summaries completed after the `counted_through` time in your running tally (see Read the window). When there is no tally for the current scanner version, it is every summary of that version. The previous run only tells you what you already reported.',
reads: `- \`vision-scanners-get\` with id \`${scannerId}\` gives \`scanner_version\`, and \`scanner_config.experiment_id\`. Read only observations of that version: a prompt edit changes what a summary looks at, so mixing versions compares two different questions.
- \`experiment-get\` with that \`experiment_id\` gives the experiment's hypothesis (its \`description\`) and the definitions of its \`metrics\`, \`metrics_secondary\` and \`saved_metrics\`. Use them only to learn which behaviors the team cares about. Do not read the experiment's results with \`experiment-results\` or any other results tool, and ignore \`conclusion\` and \`conclusion_comment\`. A metric can move for reasons no replay shows, and knowing a result makes it easy to find a story that fits it.
- \`vision-scanners-variants-list\` (scanner_id \`${scannerId}\`) gives the variant keys, each variant's observation and people counts, and its sampling rate. Those live counts are the trusted numbers: never restate them from your own reading.
-- \`vision-scanners-observations-list\` (scanner_id \`${scannerId}\`) with \`variant\` set to each key, \`status=succeeded\` and \`order_by=-completed_at\`: up to the 40 most recent summaries per variant. Read the same number from each variant where you can, so their shares compare. \`vision-observations-get\` reads one in full when its summary line is not enough.`,
- notable: `Name the themes first, across all variants at once, so a theme means the same thing in every variant: one observable behavior each ("Reopens the pricing page before checking out"). Prefer behaviors that the hypothesis and the metrics point at. Then count, per variant, how many of the summaries you read show each theme.
+- Your running tally: \`scout-scratchpad-search\` with key \`${scannerId}:pattern:variant-tally\`. It holds the \`scanner_version\` it counts, its \`counted_through\` time, and per variant how many new summaries each run found and how many it read. Per theme it holds what the theme means, the date counting started, and per variant how many summaries were read since that date, how many of them show the theme, and up to 2 example observation ids. Keep it as one JSON block so the next run reads it exactly. When there is no tally, or its \`scanner_version\` is not the current one, start an empty tally: old counts answer a different prompt, so they do not carry over.
+- The new summaries: \`execute-sql\` over \`$recording_observed\` for the current version (\`properties.scanner_version\`), with \`timestamp\` after \`counted_through\` and at or before \`now() - INTERVAL 1 HOUR\`. The hour of margin lets late events arrive, so none falls behind the cursor unread. Select \`properties.experiment_variant\`, \`properties.session_id\`, \`properties.scanner_output_title\` and \`properties.scanner_output_summary\`. First count the new summaries per variant. Then read all of them, or, when a variant has more than 50, read a sample of 50 from each variant: \`ORDER BY cityHash64(properties.session_id) LIMIT 50 BY properties.experiment_variant\`. The hash has no link to time or content, so the sample stays fair to every variant. \`vision-observations-get\` reads one in full when its summary is not enough, and \`vision-observations-list\` for a session gives the observation id to cite.`,
+ notable: `Sort each summary you read into the themes in your tally. A theme is one observable behavior ("Reopens the pricing page before checking out"), and it means the same thing in every variant. Prefer behaviors that the hypothesis and the metrics point at. Then add this window to the tally: for every theme, add the summaries you read per variant to its read count, and the ones that show the theme to its theme count.
-A difference is a theme whose share differs between variants by at least 20 percentage points (for example 14 of 40 against 6 of 40), and that you can see in the summaries themselves. A smaller gap on a few dozen summaries is noise. Your counts come from model-written summaries, so they are approximate: when you are not sure a difference is real, leave it out. Finding no difference is an acceptable result.`,
+Keep the themes fixed. Never rename, merge, or redefine a theme: its counts would then mix two meanings. A behavior that no theme covers becomes a new theme. It starts at zero on this run, records today as its start date, and counts only the summaries read from this run on. Keep the list to about 15 themes, so add a new one only for a behavior that recurs in this window.
+
+Judge differences on the tally, never on this window alone: one window is a few dozen summaries, and a gap in it is usually noise. Use the window only to say what is new. A theme is a difference only when all four of these hold:
+
+1. A two-sided Fisher exact test on its tally counts (theme count and read count minus theme count, per variant) gives a p-value below 0.05 divided by the number of tests you ran. Run the test for every theme that shows in at least 5 summaries of some variant, and count every one of those tests. With more than two variants, test each variant against control, and count each of those tests too. Compute the p-value with code (Python's \`math.comb\` is enough), never by estimate. When you cannot run code, call no theme a difference, and give the counts in the report.
+2. It shows in at least 5 summaries of the variant where it is more common.
+3. Its share differs between the variants by at least 5 percentage points, so a very large tally does not make a very small gap into a finding.
+4. You can see it in the summaries themselves.
+
+Give the p-value with each difference in the report. The themes come from summaries you read before you tested them, and a model counted them, so a p-value here is weaker evidence than one from the experiment's metrics: say so once in the report. When you are not sure a difference is real, leave it out. Finding no difference is an acceptable result.
+
+When the tally is a sample, give both numbers in the report ("counted 120 of 410 summaries"), so the reader knows the share rests on a sample.`,
quiet: 'Variants that behave the same is a real and expected result. Say so in the report, describe the themes all variants share, and record no differences.',
quietVerdict:
- 'When no theme clears the bar, still file the report: open with the verdict `No clear difference between variants`, then one line with how many summaries you read per variant, then the main themes all variants share.',
+ 'When no theme clears the bar, still file the report: open with the verdict `No clear difference between variants`, then one line with how many summaries the tally holds per variant and how many this run added, then the main themes all variants share.',
skip: `- Restating the variants counts as findings: the variants view already shows them.
-- A difference resting on fewer than 5 sessions in the variant where the theme is more common. A theme seen in 7 sessions of one variant and none of another can still be a difference.
+- A difference resting on fewer than 5 sessions in the variant where the theme is more common, or one that fails the test above.
- Effects too small to see in a few dozen sessions, such as a 1 to 2% change in watch time or conversion. Only the experiment's metrics can show those, across thousands of sessions.
- Claims about which variant wins. The experiment's metrics decide that; you describe what users do.
- Explaining, confirming, or predicting a metric result.`,
@@ -433,11 +446,13 @@ A difference is a theme whose share differs between variants by at least 20 perc
record: `Every run also records exactly one structured record with \`scout-record-output\`: the whole comparison, matching the schema in your instructions. It fills in the experiment's variants view in Replay Vision, so record it even when nothing differs.
- \`scanner_version\`: the version you read from \`vision-scanners-get\`. A record for an older version is not shown.
-- \`observations_read\`: per variant key, how many summaries you read. Every count below is out of this number.
-- \`variants\`: per variant key, up to 5 themes, most common first. \`count\` is how many of that variant's summaries you read show the theme. Cite up to 2 observation ids of that variant that show it in \`example_observation_ids\`.
-- \`differences\`: up to 5, most meaningful first, each resting on one theme, with \`counts\` per variant key. Empty when no theme clears the bar.
+- \`observations_read\`: per variant key, how many summaries the tally has read since it started. Every count below is out of this number.
+- \`variants\`: per variant key, up to 5 themes from the tally, most common first. \`count\` is the tally's count for that variant. For a theme that started after the tally did, also set \`read\` to that theme's own read count for the variant. Leave \`read\` out for a theme counted since the tally started. Cite up to 2 observation ids of that variant that show it in \`example_observation_ids\`, from the tally's examples.
+- \`differences\`: up to 5, most meaningful first, each resting on one theme, with its tally \`counts\` per variant key, and \`read\` per variant key when the theme started after the tally did. Empty when no theme clears the bar.
- Use the same \`theme\` label in every variant and in \`differences\`, so the view can line them up.
-- Submit once per run. The newest record replaces the previous one in the view.`,
+- Submit once per run. The newest record replaces the previous one in the view.
+
+Save the updated tally last, after the report and the record, under the same key. Its new \`counted_through\` is the upper bound of this run's query, not the newest timestamp you read. Then a run that fails partway reads its window again on the next run, and loses nothing.`,
}),
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 686a42553758..0dbb5d977db5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -45621,6 +45621,11 @@ export namespace Schemas {
statement: string;
/** How many of this variant's summaries the analysis read show the theme, as the scout counted them. */
count: number;
+ /**
+ * How many of this variant's summaries the theme was counted over, when that is fewer than the analysis read in total. Null when the theme was counted over every summary the analysis read.
+ * @nullable
+ */
+ read: number | null;
/** Observations of this variant the scout cited for the theme. Ids it can't back are dropped. */
example_observation_ids: string[];
}
@@ -45903,6 +45908,11 @@ export namespace Schemas {
*/
export type VariantAnalysisDifferenceCounts = {[key: string]: number};
+ /**
+ * Per variant key, how many summaries the theme was counted over, for a theme counted over fewer summaries than the analysis read in total. Empty when it was counted over all of them.
+ */
+ export type VariantAnalysisDifferenceRead = {[key: string]: number};
+
export interface VariantAnalysisDifference {
/** The theme the difference rests on. */
theme: string;
@@ -45910,6 +45920,8 @@ export namespace Schemas {
statement: string;
/** Summaries the analysis read that show the theme, per variant key, as the scout counted them. */
counts: VariantAnalysisDifferenceCounts;
+ /** Per variant key, how many summaries the theme was counted over, for a theme counted over fewer summaries than the analysis read in total. Empty when it was counted over all of them. */
+ read: VariantAnalysisDifferenceRead;
}
export interface VariantsAnalysisState {