:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments/mcp): Help agents configure metrics right the first time (#62397)
Marcel Poelkerf5386143c64e
diff --git a/ee/hogai/eval/sandboxed/experiments/eval_metric_schema_discovery.py b/ee/hogai/eval/sandboxed/experiments/eval_metric_schema_discovery.pynew file mode 100644index 000000000000..6fb0bf879ef6--- /dev/null+++ b/ee/hogai/eval/sandboxed/experiments/eval_metric_schema_discovery.py@@ -0,0 +1,64 @@+"""Eval: does the agent assemble a correctly shaped metric on the FIRST experiment-update call?++Grades whether the proactive schema guidance in the+``configuring-experiment-analytics`` skill prevents the "fail, read pydantic+error, retry" pattern from being the only path to success. Two cases:++* ``ratio_metric_uses_math_sum`` — a revenue-per-pageview ratio must aggregate+ with ``math: "sum"`` + ``math_property: "revenue"``, not an ``is_set`` filter.+* ``retention_metric_first_try`` — a 7-day retention metric must carry+ ``retention_window_start`` and ``start_handling`` up front.++``FirstUpdateMetricShape`` grades the first ``experiment-update`` call only, so+recovering on a later call does not flip the score.+"""++from __future__ import annotations++from ee.hogai.eval.sandboxed.base import SandboxedPrivateEval+from ee.hogai.eval.sandboxed.config import SandboxedEvalCase+from ee.hogai.eval.sandboxed.experiments.scorers import (+ FirstUpdateMetricShape,+ validate_ratio_revenue_metric,+ validate_retention_metric,+)+from ee.hogai.eval.sandboxed.experiments.seeders import ROLLOUT_EXPERIMENT_NAME, seed_running_experiment+from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, RequiredToolCall+++async def eval_metric_schema_discovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="ratio_metric_uses_math_sum",+ prompt=(+ f"Add a ratio metric to '{ROLLOUT_EXPERIMENT_NAME}' for total revenue (the `revenue` "+ "property on `purchase_completed`) per `$pageview`. These events aren't instrumented "+ "yet — that's intended, so allow unknown events without asking."+ ),+ setup=seed_running_experiment,+ expected={"first_update_metric_shape": validate_ratio_revenue_metric},+ ),+ SandboxedEvalCase(+ name="retention_metric_first_try",+ prompt=(+ f"Add a 7-day retention metric to '{ROLLOUT_EXPERIMENT_NAME}', `$pageview` → "+ "`uploaded_file`. These events aren't instrumented yet — that's intended, so allow "+ "unknown events without asking."+ ),+ setup=seed_running_experiment,+ expected={"first_update_metric_shape": validate_retention_metric},+ ),+ ]++ await SandboxedPrivateEval(+ experiment_name=f"sandboxed-experiments-metric-schema-discovery-{mcp_mode}",+ cases=cases,+ scorers=[+ ExitCodeZero(),+ RequiredToolCall(required={"experiment-update"}, name="called_experiment_update"),+ FirstUpdateMetricShape(),+ ],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )diff --git a/ee/hogai/eval/sandboxed/experiments/scorers.py b/ee/hogai/eval/sandboxed/experiments/scorers.pyindex 6725c98f3feb..cbbe4aa1d320 100644--- a/ee/hogai/eval/sandboxed/experiments/scorers.py+++ b/ee/hogai/eval/sandboxed/experiments/scorers.py@@ -45,6 +45,12 @@ The next three back the ``diagnosing-experiment-results`` skill (groups A–E).``CitesDiagnosticGroup``: the latter checks "did the agent identifythe small-sample / guardrail issue", this one checks "did the agentactually translate that diagnosis into 'don't ship yet' guidance".++* ``FirstUpdateMetricShape`` — deterministic. Did the agent's *first*+ ``experiment-update`` call carry a correctly shaped metric (per a+ case-supplied validator), rather than discovering the shape via a+ pydantic rejection and retrying? Backs the+ ``configuring-experiment-analytics`` skill's proactive schema guidance."""from __future__ import annotations@@ -675,6 +681,116 @@ Did the agent point to ship-variant (not end) as the right action? Answer `yes`)+class FirstUpdateMetricShape(Scorer):+ """Deterministic: did the agent's *first* experiment-update call carry a correctly shaped metric?++ Opt-in via ``expected = {"first_update_metric_shape": <validator>}`` where+ ``<validator>`` is a callable ``(metrics: list[dict]) -> tuple[bool, str]``+ returning ``(passed, reason)``. The validator runs against the ``metrics``+ array of the FIRST experiment-update call — successful or failed — so the+ score reflects whether the agent assembled the right payload up-front,+ not whether it eventually recovered after a pydantic validation error.++ Use to assert that proactive schema guidance in a skill prevented the+ "fail, read error, retry" pattern from being the only path to success.+ """++ def _name(self) -> str:+ return "first_update_metric_shape"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: Any) -> Score:+ validator = expected.get(self._name()) if isinstance(expected, dict) else None+ if not callable(validator):+ return Score(+ name=self._name(), score=1.0, metadata={"skipped": True, "reason": "Not applicable to this case"}+ )+ if not output:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No output"})++ parser = _parser_for(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ updates = sorted(parser.get_tool_calls("experiment-update"), key=lambda c: c.position)+ if not updates:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "Agent never called experiment-update"},+ )++ first = updates[0]+ raw_input = first.input if isinstance(first.input, dict) else {}+ metrics = raw_input.get("metrics") or raw_input.get("metrics_secondary") or []+ if not isinstance(metrics, list) or not metrics:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "First experiment-update had no metrics array", "call_count": len(updates)},+ )++ try:+ passed, reason = validator(metrics)+ except Exception as exc:+ return Score(name=self._name(), score=0.0, metadata={"reason": f"validator error: {exc}"})++ return Score(+ name=self._name(),+ score=1.0 if passed else 0.0,+ metadata={+ "reason": reason,+ "call_count": len(updates),+ "first_call_is_error": first.is_error,+ "first_metric": metrics[0] if metrics else None,+ },+ )+++def validate_ratio_revenue_metric(metrics: list[dict]) -> tuple[bool, str]:+ """Ratio metric: numerator must aggregate revenue via math='sum' + math_property='revenue'.++ The is_set-filter-instead-of-aggregation failure mode is caught by the math+ check: a property filter leaves math at its count default.+ """+ ratios = [m for m in metrics if isinstance(m, dict) and m.get("metric_type") == "ratio"]+ if not ratios:+ return (False, f"No ratio metric in payload (saw metric_types: {[m.get('metric_type') for m in metrics]})")+ ratio = ratios[0]+ numerator = ratio.get("numerator")+ if not isinstance(numerator, dict):+ return (False, "Ratio metric missing numerator")+ if numerator.get("math") != "sum":+ return (+ False,+ f"Numerator math is {numerator.get('math')!r}, expected 'sum' (a property filter does not aggregate)",+ )+ if numerator.get("math_property") != "revenue":+ return (False, f"Numerator math_property is {numerator.get('math_property')!r}, expected 'revenue'")+ return (True, "Numerator correctly uses math='sum' + math_property='revenue'")+++def validate_retention_metric(metrics: list[dict]) -> tuple[bool, str]:+ """Retention metric: must include retention_window_start and start_handling on the first try."""+ retentions = [m for m in metrics if isinstance(m, dict) and m.get("metric_type") == "retention"]+ if not retentions:+ return (False, f"No retention metric in payload (saw metric_types: {[m.get('metric_type') for m in metrics]})")+ retention = retentions[0]+ missing: list[str] = []+ if "retention_window_start" not in retention:+ missing.append("retention_window_start")+ if "start_handling" not in retention:+ missing.append("start_handling")+ if missing:+ return (False, f"Retention metric missing required fields: {missing}")+ return (True, "Retention metric carries retention_window_start and start_handling")++class AdvisesAgainstShipping(_BinaryJudge):"""Binary yes/no: did the agent advise against shipping (or recommend waiting)?diff --git a/ee/hogai/eval/test_sandboxed_experiment_scorers.py b/ee/hogai/eval/test_sandboxed_experiment_scorers.pynew file mode 100644index 000000000000..d2ede71ee4ed--- /dev/null+++ b/ee/hogai/eval/test_sandboxed_experiment_scorers.py@@ -0,0 +1,201 @@+"""Unit tests for the grading logic the metric-schema-discovery eval uses.++Exercises ``FirstUpdateMetricShape`` and the metric-shape validators from+``sandboxed/experiments/scorers.py`` directly, lightweight as it's given+hand-built metric dicts and synthetic ACP log lines, no sandboxed stack.++Lives one level above ``sandboxed/`` on purpose: a test under that package+inherits its ``conftest.py``, whose autouse fixtures boot the full eval harness+(Temporal, MCP, gateway, Django). Up here it stays a fast unit test.+"""++from __future__ import annotations++import json++import pytest++from braintrust import Score++from ee.hogai.eval.sandboxed.experiments.scorers import (+ FirstUpdateMetricShape,+ validate_ratio_revenue_metric,+ validate_retention_metric,+)+++def _ratio(numerator: dict, denominator: dict | None = None) -> dict:+ return {+ "kind": "ExperimentMetric",+ "metric_type": "ratio",+ "numerator": numerator,+ "denominator": denominator or {"kind": "EventsNode", "event": "$pageview"},+ }+++def _retention(**overrides) -> dict:+ metric = {+ "kind": "ExperimentMetric",+ "metric_type": "retention",+ "start_event": {"kind": "EventsNode", "event": "$pageview"},+ "completion_event": {"kind": "EventsNode", "event": "uploaded_file"},+ "retention_window_start": 0,+ "retention_window_end": 7,+ "retention_window_unit": "day",+ "start_handling": "first_seen",+ }+ metric.update(overrides)+ return metric+++RATIO_SUM = _ratio({"kind": "EventsNode", "event": "purchase_completed", "math": "sum", "math_property": "revenue"})+RATIO_IS_SET = _ratio(+ {+ "kind": "EventsNode",+ "event": "purchase_completed",+ "properties": [{"key": "revenue", "value": "is_set", "operator": "is_set", "type": "event"}],+ }+)+++ "metrics,expected_pass",+ [+ ([RATIO_SUM], True),+ ([{"metric_type": "mean", "source": {}}, RATIO_SUM], True), # ratio found alongside other metrics+ ([RATIO_IS_SET], False), # is_set filter does not aggregate+ ([_ratio({"kind": "EventsNode", "event": "purchase_completed", "math_property": "revenue"})], False), # no math+ ([_ratio({"kind": "EventsNode", "event": "purchase_completed", "math": "sum"})], False), # no math_property+ (+ [_ratio({"kind": "EventsNode", "event": "purchase_completed", "math": "sum", "math_property": "amount"})],+ False,+ ),+ ([{"metric_type": "mean", "source": {}}], False), # no ratio metric present+ ],+ ids=["sum", "sum-among-others", "is-set", "missing-math", "missing-math-property", "wrong-property", "no-ratio"],+)+def test_validate_ratio_revenue_metric(metrics: list[dict], expected_pass: bool) -> None:+ passed, reason = validate_ratio_revenue_metric(metrics)+ assert passed is expected_pass+ assert isinstance(reason, str) and reason+++ "metrics,expected_pass",+ [+ ([_retention()], True),+ ([{"metric_type": "ratio"}, _retention()], True),+ ([_retention(retention_window_start=None)], True), # required key present even if value is None+ ([{k: v for k, v in _retention().items() if k not in ("retention_window_start", "start_handling")}], False),+ ([{k: v for k, v in _retention().items() if k != "start_handling"}], False), # missing a required field+ ([{k: v for k, v in _retention().items() if k != "retention_window_start"}], False),+ ([{"metric_type": "ratio"}], False), # no retention metric present+ ],+ ids=[+ "full",+ "among-others",+ "present-none",+ "missing-both",+ "missing-start-handling",+ "missing-window-start",+ "no-retention",+ ],+)+def test_validate_retention_metric(metrics: list[dict], expected_pass: bool) -> None:+ passed, reason = validate_retention_metric(metrics)+ assert passed is expected_pass+ assert isinstance(reason, str) and reason+++def _acp_line(update: dict) -> str:+ return json.dumps(+ {+ "notification": {"method": "session/update", "params": {"update": update}},+ "timestamp": "2026-01-01T00:00:00Z",+ }+ )+++def _tool_call(call_id: str, tool_name: str, raw_input: dict, *, is_error: bool = False) -> list[str]:+ """Emit the tool_call + completing tool_call_update pair for one tool invocation."""+ return [+ _acp_line(+ {+ "sessionUpdate": "tool_call",+ "toolCallId": call_id,+ "_meta": {"claudeCode": {"toolName": tool_name}},+ "rawInput": raw_input,+ }+ ),+ _acp_line(+ {+ "sessionUpdate": "tool_call_update",+ "toolCallId": call_id,+ "status": "failed" if is_error else "completed",+ "rawOutput": "error" if is_error else "ok",+ }+ ),+ ]+++def _output(*tool_calls: list[str]) -> dict:+ lines: list[str] = []+ for call in tool_calls:+ lines.extend(call)+ return {"raw_log": "\n".join(lines), "prompt": "add a metric"}+++def _score(output: dict | None, validator=validate_ratio_revenue_metric) -> Score:+ return FirstUpdateMetricShape()._run_eval_sync(output, expected={"first_update_metric_shape": validator})+++def test_first_update_skipped_when_validator_absent() -> None:+ score = FirstUpdateMetricShape()._run_eval_sync(_output(), expected={})+ assert score.score == 1.0+ assert score.metadata.get("skipped") is True+++def test_first_update_no_output() -> None:+ assert _score(None).score == 0.0+++def test_first_update_never_called() -> None:+ score = _score(_output(_tool_call("c1", "experiment-get", {})))+ assert score.score == 0.0+ assert "never called" in score.metadata["reason"]+++def test_first_update_correct_first_try() -> None:+ score = _score(_output(_tool_call("c1", "mcp__posthog__experiment-update", {"metrics": [RATIO_SUM]})))+ assert score.score == 1.0+ assert score.metadata["call_count"] == 1+++def test_first_update_only_first_call_counts() -> None:+ # Wrong on the first call, recovered on the second — the first-try methodology must still fail it.+ score = _score(+ _output(+ _tool_call("c1", "experiment-update", {"metrics": [RATIO_IS_SET]}, is_error=True),+ _tool_call("c2", "experiment-update", {"metrics": [RATIO_SUM]}),+ )+ )+ assert score.score == 0.0+ assert score.metadata["call_count"] == 2+ assert score.metadata["first_call_is_error"] is True+++def test_first_update_error_call_still_graded_on_shape() -> None:+ # A correctly shaped payload that the API rejected for other reasons still counts as right shape.+ score = _score(_output(_tool_call("c1", "experiment-update", {"metrics": [RATIO_SUM]}, is_error=True)))+ assert score.score == 1.0+++def test_first_update_reads_metrics_secondary() -> None:+ score = _score(_output(_tool_call("c1", "experiment-update", {"metrics_secondary": [RATIO_SUM]})))+ assert score.score == 1.0+++def test_first_update_no_metrics_array() -> None:+ score = _score(_output(_tool_call("c1", "experiment-update", {"name": "renamed"})))+ assert score.score == 0.0+ assert "no metrics array" in score.metadata["reason"]diff --git a/products/experiments/skills/configuring-experiment-analytics/SKILL.md b/products/experiments/skills/configuring-experiment-analytics/SKILL.mdindex 99f9dafd58a5..903e27baac16 100644--- a/products/experiments/skills/configuring-experiment-analytics/SKILL.md+++ b/products/experiments/skills/configuring-experiment-analytics/SKILL.md@@ -94,12 +94,12 @@ RIGHT: *calls read-data-schema* → "Here are the events in your projectThere are four metric types. Each has `kind: "ExperimentMetric"`:-| metric_type | When to use | Key fields |-| ------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------- |-| `"mean"` | Average of a numeric property per user (revenue, session duration, pageviews per user) | `source` EventsNode |-| `"funnel"` | Conversion rate from exposure through one or more ordered actions | `series` array of EventsNode steps (**1 or more**) |-| `"ratio"` | Rate of one event relative to another | `numerator`, `denominator` EventsNode |-| `"retention"` | Do users come back after exposure? | `start_event`, `completion_event`, window config |+| metric_type | When to use | Required fields |+| ------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `"mean"` | Average of a numeric property per user (revenue, session duration, pageviews per user) | `source` |+| `"funnel"` | Conversion rate from exposure through one or more ordered actions | `series` (1 or more steps) |+| `"ratio"` | Rate of one event relative to another | `numerator`, `denominator` — set `math: "sum"` + `math_property` on a side to aggregate a property; filters never aggregate |+| `"retention"` | Do users come back after exposure? | `start_event`, `completion_event`, `retention_window_start`, `retention_window_end`, `retention_window_unit`, `start_handling` |**Funnel metrics and the implicit exposure step**@@ -120,7 +120,7 @@ Examples:Both can reference the same event — the difference is whether you care about count/magnitude (mean) or yes/no conversion (funnel).-See `references/metric-configuration.md` for detailed JSON examples of each type.+See `references/metric-configuration.md` for the full rendered `ExperimentMetric` schema (all four metric types, with required fields per type) plus WRONG/RIGHT JSON pairs for the failure modes that come up most often (ratio with `is_set` filter instead of `math: "sum"` + `math_property`; retention without `retention_window_start` / `start_handling`). Read it before assembling a ratio or retention payload — the required fields are authoritative.### Step 3: Primary vs secondarydiff --git a/products/experiments/skills/configuring-experiment-analytics/references/metric-configuration.md b/products/experiments/skills/configuring-experiment-analytics/references/metric-configuration.mddeleted file mode 100644index c2c7a55185b8..000000000000--- a/products/experiments/skills/configuring-experiment-analytics/references/metric-configuration.md+++ /dev/null@@ -1,125 +0,0 @@-# Metric configuration examples--All metrics use `kind: "ExperimentMetric"`. Legacy kinds (`ExperimentTrendsQuery`, `ExperimentFunnelsQuery`) are rejected.--## Mean metric--Average of a numeric property per user. Use for revenue, session duration, page views per user, etc.--```json-{- "kind": "ExperimentMetric",- "metric_type": "mean",- "name": "Average revenue per user",- "source": {- "kind": "EventsNode",- "event": "purchase_completed"- }-}-```--## Funnel metric--Conversion rate from exposure through one or more ordered actions. The experiment's exposure event is automatically prepended as `step_0`, so even a single entry in `series` creates a valid 2-step funnel (exposure → action).--### Single-step funnel (exposure → action)--```json-{- "kind": "ExperimentMetric",- "metric_type": "funnel",- "name": "Reached checkout",- "series": [{ "kind": "EventsNode", "event": "checkout_started" }]-}-```--Measures "% of exposed users who reached checkout".--### Multi-step funnel (exposure → action 1 → action 2 → ...)--```json-{- "kind": "ExperimentMetric",- "metric_type": "funnel",- "name": "Checkout conversion",- "series": [- { "kind": "EventsNode", "event": "add_to_cart" },- { "kind": "EventsNode", "event": "checkout_started" },- { "kind": "EventsNode", "event": "purchase_completed" }- ]-}-```--Step order matters — users must complete steps in sequence.--## Ratio metric--Rate of one event relative to another. Use for click-through rates, error rates, engagement ratios.--```json-{- "kind": "ExperimentMetric",- "metric_type": "ratio",- "name": "Click-through rate",- "numerator": {- "kind": "EventsNode",- "event": "button_clicked"- },- "denominator": {- "kind": "EventsNode",- "event": "$pageview"- }-}-```--## Retention metric--Whether users return after initial exposure. Use for measuring long-term engagement.--```json-{- "kind": "ExperimentMetric",- "metric_type": "retention",- "name": "7-day retention",- "start_event": {- "kind": "EventsNode",- "event": "$feature_flag_called"- },- "completion_event": {- "kind": "EventsNode",- "event": "$pageview"- },- "retention_window_start": 0,- "retention_window_end": 7,- "retention_window_unit": "day"-}-```--## Adding metrics to an experiment--Call `experiment-update` with the full `metrics` array. This **replaces** the entire list.--To add a metric without losing existing ones:--1. Call `experiment-get` to get current metrics-2. Append the new metric to the existing array-3. Call `experiment-update` with the combined array--## Property filters--Any EventsNode can include property filters to narrow which events count:--```json-{- "kind": "EventsNode",- "event": "purchase_completed",- "properties": [- {- "key": "plan",- "value": ["pro", "enterprise"],- "operator": "exact",- "type": "event"- }- ]-}-```diff --git a/products/experiments/skills/configuring-experiment-analytics/references/metric-configuration.md.j2 b/products/experiments/skills/configuring-experiment-analytics/references/metric-configuration.md.j2new file mode 100644index 000000000000..11b92bc764c5--- /dev/null+++ b/products/experiments/skills/configuring-experiment-analytics/references/metric-configuration.md.j2@@ -0,0 +1,230 @@+# Metric configuration++All metrics use `kind: "ExperimentMetric"`. Legacy kinds (`ExperimentTrendsQuery`, `ExperimentFunnelsQuery`) are rejected.++The full Pydantic schema below is rendered from `posthog/schema.py` at build+time — if a field is missing here, fix the model. It is the `ExperimentMetric`+discriminated union: pick the variant matching your `metric_type` (`mean`,+`funnel`, `ratio`, `retention`) under `$defs`, and read that variant's+`required` array for the mandatory fields. The shared event-source building+blocks (`EventsNode`, `ActionsNode`, `ExperimentDataWarehouseNode`) and the+property-filter types are defined once under `$defs` and referenced by `$ref`.+The schema is authoritative; the prose and examples below are guidance.++## Schema++```json+{{ pydantic_schema("posthog.schema.ExperimentMetric") }}+```++## Mean metric++Average of a numeric property per user. Use for revenue per user, session+duration, page views per user, and similar magnitudes. Drives the math via the+`source.math` / `source.math_property` pair on a single `EventsNode`,+`ActionsNode`, or `ExperimentDataWarehouseNode`.++### Right++```json+{+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "name": "Average revenue per user",+ "source": {+ "kind": "EventsNode",+ "event": "purchase_completed",+ "math": "sum",+ "math_property": "revenue"+ }+}+```++## Funnel metric++Conversion rate from exposure through one or more ordered actions. The+experiment's exposure event is automatically prepended as `step_0`, so even a+single entry in `series` creates a valid 2-step funnel (exposure → action).++### Right — single-step funnel (exposure → action)++```json+{+ "kind": "ExperimentMetric",+ "metric_type": "funnel",+ "name": "Reached checkout",+ "series": [{ "kind": "EventsNode", "event": "checkout_started" }]+}+```++Measures "% of exposed users who reached checkout".++### Right — multi-step funnel (exposure → action 1 → action 2 → ...)++```json+{+ "kind": "ExperimentMetric",+ "metric_type": "funnel",+ "name": "Checkout conversion",+ "series": [+ { "kind": "EventsNode", "event": "add_to_cart" },+ { "kind": "EventsNode", "event": "checkout_started" },+ { "kind": "EventsNode", "event": "purchase_completed" }+ ]+}+```++Step order matters — users must complete steps in sequence.++## Ratio metric++Rate of one event relative to another. Each side (`numerator`, `denominator`)+is an `EventsNode` / `ActionsNode` / `ExperimentDataWarehouseNode` with its own+`math` and `math_property` — the math determines how each side is aggregated+before the ratio is taken.++Use for revenue per pageview, click-through rate, error rate, engagement+ratios.++### Right — click-through rate (count / count)++```json+{+ "kind": "ExperimentMetric",+ "metric_type": "ratio",+ "name": "Click-through rate",+ "numerator": {+ "kind": "EventsNode",+ "event": "button_clicked"+ },+ "denominator": {+ "kind": "EventsNode",+ "event": "$pageview"+ }+}+```++### Right — revenue per pageview (sum of property / count)++To divide a property sum by an event count, the numerator's `math` is `"sum"`+and `math_property` names the numeric property to sum. The denominator stays+at the default count.++```json+{+ "kind": "ExperimentMetric",+ "metric_type": "ratio",+ "name": "Revenue per pageview",+ "numerator": {+ "kind": "EventsNode",+ "event": "purchase_completed",+ "math": "sum",+ "math_property": "revenue"+ },+ "denominator": {+ "kind": "EventsNode",+ "event": "$pageview"+ }+}+```++### Wrong — `is_set` filter instead of `math` / `math_property`++```json+{+ "kind": "ExperimentMetric",+ "metric_type": "ratio",+ "name": "Revenue per pageview",+ "numerator": {+ "kind": "EventsNode",+ "event": "purchase_completed",+ "properties": [+ { "key": "revenue", "value": "is_set", "operator": "is_set", "type": "event" }+ ]+ },+ "denominator": { "kind": "EventsNode", "event": "$pageview" }+}+```++A property filter scopes *which events* count — it does not sum them. The+numerator above counts purchases that have a revenue property, not the revenue+total. Aggregation lives in `math` / `math_property`, never in a filter.++## Retention metric++Whether users return after initial exposure. Tracks `start_event` →+`completion_event` over a window defined by `retention_window_start`,+`retention_window_end`, and `retention_window_unit`. `start_handling` is+required and controls how users with multiple start events are anchored:+`"first_seen"` (anchor on first occurrence) or `"last_seen"` (anchor on most+recent).++### Right — 7-day retention++```json+{+ "kind": "ExperimentMetric",+ "metric_type": "retention",+ "name": "7-day retention",+ "start_event": {+ "kind": "EventsNode",+ "event": "$pageview"+ },+ "completion_event": {+ "kind": "EventsNode",+ "event": "uploaded_file"+ },+ "retention_window_start": 0,+ "retention_window_end": 7,+ "retention_window_unit": "day",+ "start_handling": "first_seen"+}+```++### Wrong — missing `retention_window_start` and `start_handling`++```json+{+ "kind": "ExperimentMetric",+ "metric_type": "retention",+ "name": "7-day retention",+ "start_event": { "kind": "EventsNode", "event": "$pageview" },+ "completion_event": { "kind": "EventsNode", "event": "uploaded_file" },+ "retention_window_end": 7,+ "retention_window_unit": "day"+}+```++Pydantic rejects the payload with a missing-field error. Both fields are+required on every retention metric — the schema is the source of truth.++## Adding metrics to an experiment++Call `experiment-update` with the full `metrics` array. This **replaces** the+entire list.++To add a metric without losing existing ones:++1. Call `experiment-get` to get current metrics+2. Append the new metric to the existing array+3. Call `experiment-update` with the combined array++## Property filters++Any `EventsNode` can include property filters to narrow *which* events count.+Filters never change aggregation — for that, use `math` / `math_property`.++```json+{+ "kind": "EventsNode",+ "event": "purchase_completed",+ "properties": [+ {+ "key": "plan",+ "value": ["pro", "enterprise"],+ "operator": "exact",+ "type": "event"+ }+ ]+}+```