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.

fix(signals): prevent unreadable report measurements (#108617)

Mikayla Thompsonf6b58310caed
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index e898c4a90069..0bb9f0c9c841 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -24,7 +24,7 @@ It also skips a plan that carries its own open, draft, or unknown PR, because th
## Proposed impact measurement
-The organization authoring flag lets research propose up to six active `impact_measurement_plan` artefacts for measurable outcomes. Each bounded query, goal, aggregation grain, and decision rule lives in an artefact, not in the report's observation metrics. A minimum-data rule also needs an eligibility query for qualifying opportunities. A later research pass reviews the current plans against new evidence. It preserves unchanged plans, appends an unapproved version for a material revision, or appends a retired version when the outcome is no longer relevant or measurable. A plan changed by a person during research takes precedence over that pass. Earlier versions remain for review. The report's "Keep an eye on this for me" action activates current proposals when the display flag is on. Activation appends a new version and does not schedule a check or change the report state. The approval action currently accepts an authenticated person; the artefact schema does not require a person as its approver.
+The organization authoring flag lets research propose up to six active `impact_measurement_plan` artefacts for measurable outcomes. Each bounded query, goal, aggregation grain, and decision rule lives in an artefact, not in the report's observation metrics. Authoring rejects query filters and conversion goals whose shape the report access policy cannot check, including HogQL property filters. It also omits an observation metric when its query has an unsupported filter; research keeps that evidence in report prose when no readable structured query exists. A readable observation remains without a plan when only the eligibility query is unsupported. Individual resource grants, token scopes, and property restrictions still apply when someone reads a report. A minimum-data rule also needs an eligibility query for qualifying opportunities. A later research pass reviews the current plans against new evidence. It preserves unchanged plans, appends an unapproved version for a material revision, or appends a retired version when the outcome is no longer relevant or measurable. A plan changed by a person during research takes precedence over that pass. Earlier versions remain for review. The report's "Keep an eye on this for me" action activates current proposals when the display flag is on. Activation appends a new version and does not schedule a check or change the report state. The approval action currently accepts an authenticated person; the artefact schema does not require a person as its approver.
## Repository selection
diff --git a/products/signals/backend/impact_measurement_plans.py b/products/signals/backend/impact_measurement_plans.py
index ff9b70a4d126..e31a31f87c08 100644
--- a/products/signals/backend/impact_measurement_plans.py
+++ b/products/signals/backend/impact_measurement_plans.py
@@ -9,11 +9,21 @@ import structlog
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import ImpactMeasurementPlan
from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.report_metric_query_access import query_filter_shape_allows_read
from products.signals.backend.report_metrics import MAX_REPORT_METRICS, REPORT_METRIC_GOAL_FIELDS
logger = structlog.get_logger(__name__)
+def validate_authored_measurement_plan(plan: ImpactMeasurementPlan) -> None:
+ if plan.retired:
+ return
+ if not query_filter_shape_allows_read(plan.query):
+ raise ValueError("measurement query filters cannot be checked for viewer access; HogQL filters are unsupported")
+ if plan.eligibility_query is not None and not query_filter_shape_allows_read(plan.eligibility_query):
+ raise ValueError("eligibility query filters cannot be checked for viewer access; HogQL filters are unsupported")
+
+
def latest_measurement_plans(report: SignalReport) -> dict[str, tuple[SignalReportArtefact, ImpactMeasurementPlan]]:
plans: dict[str, tuple[SignalReportArtefact, ImpactMeasurementPlan]] = {}
rows = SignalReportArtefact.objects.filter(
@@ -59,6 +69,14 @@ def persist_authored_measurement_plans(
logger.warning("ignoring conflicting impact measurement decisions", report_id=str(report.id))
clean_metrics = []
for metric in metrics:
+ query = metric.get("query")
+ if not isinstance(query, Mapping) or not query_filter_shape_allows_read(query):
+ logger.warning(
+ "ignoring report metric with unreadable query shape",
+ report_id=str(report.id),
+ metric_id=metric.get("metric_id"),
+ )
+ continue
clean_metrics.append({key: value for key, value in metric.items() if key not in REPORT_METRIC_GOAL_FIELDS})
if metric.get("goal_value") is None or metric.get("goal_direction") is None:
continue
@@ -98,6 +116,7 @@ def persist_authored_measurement_plans(
"activated": False,
}
)
+ validate_authored_measurement_plan(plan)
except ValueError:
logger.warning(
"ignoring invalid proposed impact measurement", report_id=str(report.id), metric_id=metric_id
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.md
index 1b85af491478..93db3c8ed621 100644
--- a/products/signals/backend/report_generation/AGENTS.md
+++ b/products/signals/backend/report_generation/AGENTS.md
@@ -97,7 +97,7 @@ The presentation step can also author up to six typed `metrics` alongside the pr
- **Affected people and sessions are distinct.** An `affected_users` metric uses exactly one event or action series with `math: "dau"`. An `affected_sessions` metric uses exactly one event or action series with `math: "unique_session"`. Neither kind uses formulas, group math, breakdowns, or compare mode. Never sum interval buckets.
- **One bounded live measurement.** Every metric has a live query built only from event or action sources, rejects breakdown and compare mode, and must produce exactly one output series. Without a formula that means exactly one source. A conversion or rate may combine at most ten event/action sources through exactly one formula output. The longitudinal result is capped at 1,000 estimated interval points, including the current partial bucket.
-- **A malformed optional goal does not cost the whole report.** Before parsing the presentation, an invalid goal is stripped when the underlying observation metric is still valid; an invalid observation metric still fails the presentation. `_resolve_report_metrics_payload` checks whole-set rules (count, total query characters, duplicate ids, one primary, one affected-users). Research can propose goals only under the separate organization authoring flag. The ready or pending-input transition moves them to versioned `impact_measurement_plan` artefacts and stores goal-free observations in report metrics. On re-research, the agent reviews current plans and explicitly identifies material revisions or retirements; unchanged plans keep their version and approval. A revision appends an unapproved version, and a retirement appends a retired version. A concurrent manual edit takes precedence over the research decision. Activating a plan appends an approved version but does not schedule a check.
+- **A malformed optional goal does not cost the whole report.** Before parsing the presentation, an invalid goal is stripped when the underlying observation metric is still valid; an invalid observation metric still fails the presentation. `_resolve_report_metrics_payload` checks whole-set rules (count, total query characters, duplicate ids, one primary, one affected-users). Research can propose goals only under the separate organization authoring flag. The ready or pending-input transition moves them to versioned `impact_measurement_plan` artefacts and stores goal-free observations in report metrics. Authoring omits observations whose query filters the report access policy cannot inspect, including HogQL property filters. If only a goal's eligibility query is unreadable, the readable observation remains without a plan. On re-research, the agent reviews current plans and explicitly identifies material revisions or retirements; unchanged plans keep their version and approval. A revision appends an unapproved version, and a retirement appends a retired version. A concurrent manual edit takes precedence over the research decision. Activating a plan appends an approved version but does not schedule a check.
- **Consumers own the display.** Authored Trends display is not the report presentation contract. Consumers derive `BoldNumber` for the first output series' whole-window `aggregated_value` and `ActionsBar` for longitudinal buckets. Every metric runs through both derived shapes and the normal query cache. The inbox does not maintain a separate time-series table.
- **Snapshots are optional fallbacks.** `value` and `value_at` travel together, preserve zero as measured data, and never replace the live query. `value_at` is stored in UTC, whatever offset the author wrote; a measurement time still ahead of the server clock drops the snapshot and keeps the metric, so an unusable timestamp never costs the report. Opening the inbox list or a report refreshes the stale snapshots on screen through the query cache without changing report ordering; there is no background job. Snapshot-only or queryless rows are legacy or malformed and are always redacted.
- **Independent opt-in.** Metrics use the organization-level `signals-report-metrics` flag (`report_content_gates.py`, on in DEBUG). Charts do not require a feature flag. When off, pipeline metric guidance and schema fields are removed and the caller preserves existing metrics. Every writer reads the flag, including the scout report channel, which drops a supplied set before the safety judge. Scout-authored metrics are safety-judged with the rest of the report.
diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.py
index 89b931a7cd58..f7aea88a9a16 100644
--- a/products/signals/backend/report_generation/research.py
+++ b/products/signals/backend/report_generation/research.py
@@ -809,6 +809,7 @@ Put reproducible report-level measurements under `metrics`. A metric tells the r
- **Prefer affected users when the data supports it.** `affected_users` means unique PostHog people matching the observation during the query's declared window. Use one `InsightVizNode` wrapping a single-series `TrendsQuery` with `math: "dau"` and a bounded `dateRange.date_from`. An `EventsNode` needs a non-empty `event`; an `ActionsNode` needs a positive integer `id`. Never sum daily or hourly unique-user buckets because one person may appear in several buckets.
- **Use the honest entity.** If the source can only establish sessions, traces, requests, tickets, or events, label and type that measurement instead of calling it users. Do not guess identity mappings. Omit a metric that cannot be measured; missing is not zero. A weak number is worse than none: a single support ticket, a one-off migration crash, a rate over a handful of attempts, or a count with no person context tells the reader nothing, so a report with no metric beats a report with a weak metric.
- **Keep every metric live and bounded.** Give every metric an `InsightVizNode` wrapping a `TrendsQuery` you successfully ran in this research session. Every source series must be an `EventsNode` or `ActionsNode`. Use a relative window no longer than {MAX_LIVE_METRIC_WINDOW_DAYS} days and leave `date_to` empty. Default the query to `dateRange.date_from: "{DEFAULT_LIVE_METRIC_DATE_FROM}"` with `interval: "day"`. This gives 14 inclusive daily buckets, including today. The inbox strip shows at most the trailing 14 buckets. For a longer window, the strip is shorter than the whole-window figure and the caption says why the longer window is needed. The longitudinal output may contain at most {MAX_LIVE_METRIC_QUERY_POINTS} estimated interval points, including the current partial bucket.
+- **Use filters the report can show.** Use structured property filters, not `hogql` property filters, in every metric query. If the evidence needs a HogQL filter and no equivalent structured query exists, describe the verified evidence in report prose and omit the metric. The report cannot show an observation whose query uses an unsupported filter.
- **Consumers own the display.** The stored Trends definition remains the source of truth, but its authored display is not. Consumers derive `BoldNumber` for the first output series' whole-window `aggregated_value` and `ActionsBar` for its longitudinal buckets. Run the total-value shape when you author a snapshot; a bar or line response does not supply the whole-window total.
- **Keep exactly one output series per query.** Do not use a breakdown or compare mode on any report metric. Without a formula, use exactly one source series. A conversion or rate may use up to {MAX_LIVE_METRIC_QUERY_SERIES} event/action source series as formula inputs, but it must define exactly one formula output.
- **Snapshots are optional cached fallbacks.** Send `value` and `value_at` together only for a value you observed, and write `value_at` as an ISO-8601 timestamp with a timezone. Any offset works, because the server reads it as one instant and stores it in UTC, but a time ahead of the server clock drops the snapshot and keeps the metric. Zero is valid measured data. Null means no snapshot. Never invent a value from prose or estimate one from grouped signal count. A snapshot cannot replace the required live query. When you also ran the bar shape, `series` may carry its trailing per-bucket values, oldest first, at most {MAX_METRIC_SERIES_POINTS} points; the inbox row draws them as a small trend strip.
@@ -820,6 +821,7 @@ Put reproducible report-level measurements under `metrics`. A metric tells the r
_EXPECTED_IMPACT_GUIDANCE = """## Proposed impact measurement
When the solution has an Expected impact section and the research supports it, give one live metric that directly measures the intended change a `goal_value` and `goal_direction` (`at_most` or `at_least`). Suggest `decision_window_days` (1–30) based on observed traffic. Set `minimum_data_points` (1–1000) only when you can also supply a bounded `eligibility_query`. Count qualifying opportunities, not failures: a zero-failure goal cannot require failures to occur. Prefer a short useful window over waiting for certainty. State the baseline and intended outcome in the Expected impact prose. The goal is a proposal, not a scheduled check or a statistical confidence claim. If the metric cannot observe the intended outcome, or no credible threshold or traffic estimate exists, omit the goal rather than invent one. Keep an existing valid goal on re-research unless evidence changes it.
+For a proposed goal and its eligibility query, use structured property filters. Do not use `hogql` property filters: the report cannot show their query definitions to viewers, so authoring rejects the proposal. If only the eligibility query needs an unsupported filter, omit the goal and keep the observation only when its own query is readable.
Choose `goal_grain=per_interval` only when the threshold applies to each chart bucket; otherwise use `whole_window`. The proposal is saved as an impact measurement artefact separate from the report's observation metrics. Do not call it statistically significant without a suitable test.
"""
diff --git a/products/signals/backend/report_metric_access.py b/products/signals/backend/report_metric_access.py
index 950aec60a2b0..919c00c11fe1 100644
--- a/products/signals/backend/report_metric_access.py
+++ b/products/signals/backend/report_metric_access.py
@@ -23,20 +23,11 @@ from products.access_control.backend.facade.user_access_control import ACCESS_CO
from products.access_control.backend.property_access_control import (
get_restricted_properties_with_group_type_index_for_team,
)
-
-_ORDINARY_PROPERTY_FILTER_TYPES = frozenset(
- {
- "element",
- "event",
- "group",
- "person",
- "person_metadata",
- "session",
- }
+from products.signals.backend.report_metric_query_access import (
+ conversion_goal_has_readable_shape,
+ property_filters_allow_read,
)
-_MAX_PROPERTY_FILTER_DEPTH = 20
-
class ReportMetricAccessPolicy:
"""Decide which data-bearing fields of a report metric this request may read."""
@@ -109,23 +100,14 @@ class ReportMetricAccessPolicy:
conversion_goal = source.get("conversionGoal")
if conversion_goal is not None:
- if not isinstance(conversion_goal, Mapping):
+ if not isinstance(conversion_goal, Mapping) or not conversion_goal_has_readable_shape(conversion_goal):
return False
if "actionId" in conversion_goal:
- if set(conversion_goal) != {"actionId"} or not self._may_read_resource_id(
- "action", conversion_goal["actionId"]
- ):
+ if not self._may_read_resource_id("action", conversion_goal["actionId"]):
return False
elif "customEventName" in conversion_goal:
- if (
- set(conversion_goal) != {"customEventName"}
- or not isinstance(conversion_goal["customEventName"], str)
- or not conversion_goal["customEventName"]
- or not self._token_grants("event_definition")
- ):
+ if not self._token_grants("event_definition"):
return False
- else:
- return False
return True
@@ -192,32 +174,9 @@ class ReportMetricAccessPolicy:
return resource_key in access_control.allowlisted_resource_ids_by_scope.get(resource, frozenset())
def _may_read_property_filters(self, filters: object) -> bool:
- if filters is None:
- return True
- pending: list[tuple[object, int]]
- if isinstance(filters, list):
- pending = [(item, 0) for item in filters]
- elif isinstance(filters, Mapping) and filters.get("type") in ("AND", "OR"):
- pending = [(filters, 0)]
- else:
- return False
-
- while pending:
- item, depth = pending.pop()
- if not isinstance(item, Mapping) or depth > _MAX_PROPERTY_FILTER_DEPTH:
- return False
- filter_type = item.get("type")
- if filter_type in ("AND", "OR"):
- values = item.get("values")
- if not isinstance(values, list):
- return False
- pending.extend((value, depth + 1) for value in values)
- elif filter_type == "cohort":
- if item.get("key") != "id" or not self._may_read_resource_id("cohort", item.get("value")):
- return False
- elif not isinstance(filter_type, str) or filter_type not in _ORDINARY_PROPERTY_FILTER_TYPES:
- return False
- return True
+ return property_filters_allow_read(
+ filters, may_read_cohort=lambda cohort_id: self._may_read_resource_id("cohort", cohort_id)
+ )
@staticmethod
def _trends_series(query: object) -> Sequence[Mapping[str, object]] | None:
diff --git a/products/signals/backend/report_metric_query_access.py b/products/signals/backend/report_metric_query_access.py
new file mode 100644
index 000000000000..8ba54b4dc985
--- /dev/null
+++ b/products/signals/backend/report_metric_query_access.py
@@ -0,0 +1,79 @@
+"""Query shapes the report metric read policy can inspect for viewer access."""
+
+from collections.abc import Callable, Mapping
+
+ORDINARY_PROPERTY_FILTER_TYPES = frozenset({"element", "event", "group", "person", "person_metadata", "session"})
+MAX_PROPERTY_FILTER_DEPTH = 20
+
+
+def property_filters_allow_read(filters: object, *, may_read_cohort: Callable[[int], bool] | None = None) -> bool:
+ if filters is None:
+ return True
+ pending: list[tuple[object, int]]
+ if isinstance(filters, list):
+ pending = [(item, 0) for item in filters]
+ elif isinstance(filters, Mapping) and filters.get("type") in ("AND", "OR"):
+ pending = [(filters, 0)]
+ else:
+ return False
+
+ while pending:
+ item, depth = pending.pop()
+ if not isinstance(item, Mapping) or depth > MAX_PROPERTY_FILTER_DEPTH:
+ return False
+ filter_type = item.get("type")
+ if filter_type in ("AND", "OR"):
+ values = item.get("values")
+ if not isinstance(values, list):
+ return False
+ pending.extend((value, depth + 1) for value in values)
+ elif filter_type == "cohort":
+ cohort_id = item.get("value")
+ if (
+ item.get("key") != "id"
+ or not isinstance(cohort_id, int)
+ or isinstance(cohort_id, bool)
+ or cohort_id <= 0
+ or (may_read_cohort is not None and not may_read_cohort(cohort_id))
+ ):
+ return False
+ elif not isinstance(filter_type, str) or filter_type not in ORDINARY_PROPERTY_FILTER_TYPES:
+ return False
+ return True
+
+
+def conversion_goal_has_readable_shape(goal: object) -> bool:
+ if goal is None:
+ return True
+ if not isinstance(goal, Mapping):
+ return False
+ if "actionId" in goal:
+ action_id = goal["actionId"]
+ return (
+ set(goal) == {"actionId"}
+ and isinstance(action_id, int)
+ and not isinstance(action_id, bool)
+ and action_id > 0
+ )
+ return (
+ set(goal) == {"customEventName"}
+ and isinstance(goal.get("customEventName"), str)
+ and bool(goal["customEventName"])
+ )
+
+
+def query_filter_shape_allows_read(query: Mapping[str, object]) -> bool:
+ source = query.get("source")
+ if not isinstance(source, Mapping):
+ return False
+ series = source.get("series")
+ if not isinstance(series, list) or any(not isinstance(item, Mapping) for item in series):
+ return False
+ for item in series:
+ for field in ("properties", "fixedProperties"):
+ if field in item and not property_filters_allow_read(item[field]):
+ return False
+ for field in ("properties", "fixedProperties"):
+ if field in source and not property_filters_allow_read(source[field]):
+ return False
+ return conversion_goal_has_readable_shape(source.get("conversionGoal"))
diff --git a/products/signals/backend/test/test_artefact_schemas.py b/products/signals/backend/test/test_artefact_schemas.py
index 07140f58a8bf..4f467719a8ea 100644
--- a/products/signals/backend/test/test_artefact_schemas.py
+++ b/products/signals/backend/test/test_artefact_schemas.py
@@ -1,4 +1,6 @@
import json
+from copy import deepcopy
+from typing import NotRequired, TypedDict
from django.test import SimpleTestCase
@@ -21,29 +23,74 @@ from products.signals.backend.artefact_schemas import (
artefact_type_for,
parse_artefact_content,
)
+from products.signals.backend.impact_measurement_plans import validate_authored_measurement_plan
from products.signals.backend.models import SignalReportArtefact
+class _FilterFixture(TypedDict):
+ type: str
+ key: str
+ value: str
+
+
+class _SeriesFixture(TypedDict):
+ kind: str
+ event: str
+ math: str
+ properties: NotRequired[list[_FilterFixture]]
+ fixedProperties: NotRequired[list[_FilterFixture]]
+
+
+class _SourceFixture(TypedDict):
+ kind: str
+ dateRange: dict[str, str]
+ series: list[_SeriesFixture]
+ trendsFilter: dict[str, str]
+ properties: NotRequired[list[_FilterFixture]]
+
+
+class _QueryFixture(TypedDict):
+ kind: str
+ source: _SourceFixture
+
+
+class _ImpactPlanFixture(TypedDict):
+ metric_id: str
+ title: str
+ kind: str
+ value_format: str
+ query: _QueryFixture
+ goal_value: int
+ goal_direction: str
+ decision_window_days: int
+ minimum_data_points: NotRequired[int]
+ eligibility_query: NotRequired[_QueryFixture]
+
+
+def _impact_plan() -> _ImpactPlanFixture:
+ return {
+ "metric_id": "errors",
+ "title": "Errors",
+ "kind": "occurrences",
+ "value_format": "count",
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "dateRange": {"date_from": "-7d"},
+ "series": [{"kind": "EventsNode", "event": "$exception", "math": "total"}],
+ "trendsFilter": {"display": "ActionsBar"},
+ },
+ },
+ "goal_value": 0,
+ "goal_direction": "at_most",
+ "decision_window_days": 7,
+ }
+
+
class TestArtefactSchemas(SimpleTestCase):
def test_impact_plan_rejects_boolean_decision_rules(self) -> None:
- plan = {
- "metric_id": "errors",
- "title": "Errors",
- "kind": "occurrences",
- "value_format": "count",
- "query": {
- "kind": "InsightVizNode",
- "source": {
- "kind": "TrendsQuery",
- "dateRange": {"date_from": "-7d"},
- "series": [{"kind": "EventsNode", "event": "$exception", "math": "total"}],
- "trendsFilter": {"display": "ActionsBar"},
- },
- },
- "goal_value": 0,
- "goal_direction": "at_most",
- "decision_window_days": 7,
- }
+ plan = _impact_plan()
ImpactMeasurementPlan.model_validate(plan)
for field in ("goal_value", "decision_window_days", "minimum_data_points"):
for boolean in (True, False):
@@ -51,6 +98,41 @@ class TestArtefactSchemas(SimpleTestCase):
ImpactMeasurementPlan.model_validate({**plan, field: boolean})
self.assertIn(field, str(caught.exception))
+ def test_impact_plan_authoring_rejects_unreadable_query_filters(self) -> None:
+ for location, field in (("series", "properties"), ("series", "fixedProperties"), ("source", "properties")):
+ with self.subTest(location=location, field=field):
+ plan = _impact_plan()
+ unreadable_filter: _FilterFixture = {
+ "type": "hogql",
+ "key": "properties.secret",
+ "value": "secret",
+ }
+ if location == "source":
+ plan["query"]["source"]["properties"] = [unreadable_filter]
+ elif field == "fixedProperties":
+ plan["query"]["source"]["series"][0]["fixedProperties"] = [unreadable_filter]
+ else:
+ plan["query"]["source"]["series"][0]["properties"] = [unreadable_filter]
+
+ existing_plan = ImpactMeasurementPlan.model_validate(plan)
+ with self.assertRaisesRegex(ValueError, "HogQL filters are unsupported"):
+ validate_authored_measurement_plan(existing_plan)
+
+ supported = _impact_plan()
+ supported["query"]["source"]["series"][0]["properties"] = [
+ {"type": "event", "key": "$current_url", "value": "https://example.com/errors"}
+ ]
+ validate_authored_measurement_plan(ImpactMeasurementPlan.model_validate(supported))
+
+ eligibility = _impact_plan()
+ eligibility["minimum_data_points"] = 10
+ eligibility["eligibility_query"] = deepcopy(eligibility["query"])
+ eligibility["eligibility_query"]["source"]["series"][0]["properties"] = [
+ {"type": "hogql", "key": "properties.secret", "value": "secret"}
+ ]
+ with self.assertRaisesRegex(ValueError, "eligibility query filters cannot be checked"):
+ validate_authored_measurement_plan(ImpactMeasurementPlan.model_validate(eligibility))
+
def test_reviewer_reasons_are_bounded_on_write(self):
with self.assertRaises(ValidationError):
SuggestedReviewerEntry(github_login="reviewer", reason="x" * 501)
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
index 79939fc597e8..da5e030fdc51 100644
--- a/products/signals/backend/test/test_signal_report_artefact_api.py
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -18,6 +18,7 @@ from posthog.models.user import User
from products.signals.backend.artefact_schemas import (
DISMISSAL_NOTE_MAX_LENGTH,
CodeReference,
+ ImpactMeasurementPlan,
NoteArtefact,
Priority,
PriorityAssessment,
@@ -103,6 +104,61 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
persist_authored_measurement_plans(report, [self._impact_plan()], ArtefactAttribution.system())
assert SignalReportArtefact.objects.filter(report=report, type="impact_measurement_plan").count() == 1
+ def test_impact_plan_authoring_rejects_query_the_report_would_hide(self) -> None:
+ report = self._create_report()
+ plan = self._impact_plan()
+ plan["query"]["source"]["series"][0]["properties"] = [
+ {"type": "hogql", "key": "properties.secret", "value": "secret"}
+ ]
+
+ response = self.client.post(
+ self._list_url(str(report.id)), {"artefact_type": "impact_measurement_plan", "content": plan}, format="json"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "HogQL filters are unsupported" in response.json()["error"]
+
+ observations = persist_authored_measurement_plans(report, [plan], ArtefactAttribution.system())
+ assert observations == []
+ assert latest_measurement_plans(report) == {}
+
+ goal_free_observation = {
+ key: value
+ for key, value in plan.items()
+ if key not in ("goal_value", "goal_direction", "decision_window_days")
+ }
+ assert persist_authored_measurement_plans(report, [goal_free_observation], ArtefactAttribution.system()) == []
+
+ readable_plan = self._impact_plan()
+ eligibility_query = json.loads(json.dumps(plan["query"]))
+ eligibility_query["source"]["series"][0]["math"] = "total"
+ readable_plan["eligibility_query"] = eligibility_query
+ readable_plan["minimum_data_points"] = 10
+ observations = persist_authored_measurement_plans(report, [readable_plan], ArtefactAttribution.system())
+ assert len(observations) == 1
+ assert "goal_value" not in observations[0]
+ assert observations[0]["query"] == readable_plan["query"]
+ assert latest_measurement_plans(report) == {}
+
+ def test_existing_unreadable_impact_plan_remains_available_for_revision(self) -> None:
+ report = self._create_report()
+ plan = self._impact_plan()
+ plan["query"]["source"]["series"][0]["properties"] = [
+ {"type": "hogql", "key": "properties.secret", "value": "secret"}
+ ]
+ SignalReportArtefact.add_log(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=ImpactMeasurementPlan.model_validate(plan),
+ attribution=ArtefactAttribution.system(),
+ )
+
+ assert "affected-users" in latest_measurement_plans(report)
+ response = self.client.get(self._list_url(str(report.id)))
+ content = response.json()["results"][0]["content"]
+ assert content["title"] == "Affected users"
+ assert "query" not in content
+ assert "goal_value" not in content
+
def test_impact_plan_limits_active_outcomes_but_allows_revisions_and_replacements(self) -> None:
report = self._create_report()
url = self._list_url(str(report.id))
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 29deef3688aa..305658e24f7f 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -101,7 +101,11 @@ from products.signals.backend.billing import (
from products.signals.backend.dismissal_notes import forward_dismissal_note
from products.signals.backend.facade.api import emit_signal
from products.signals.backend.feedback_notes import forward_feedback_note
-from products.signals.backend.impact_measurement_plans import can_append_measurement_plan, latest_measurement_plans
+from products.signals.backend.impact_measurement_plans import (
+ can_append_measurement_plan,
+ latest_measurement_plans,
+ validate_authored_measurement_plan,
+)
from products.signals.backend.implementation_pr import (
fetch_implementation_prs_for_reports,
implementation_pr_report_filter,
@@ -4883,10 +4887,15 @@ class SignalReportArtefactViewSet(
{"error": f"content does not match the '{artefact_type}' schema: {e}"},
status=status.HTTP_400_BAD_REQUEST,
)
- if isinstance(parsed_content, ImpactMeasurementPlan) and parsed_content.activated:
- return Response(
- {"error": "Activate a measurement with its approval action."}, status=status.HTTP_400_BAD_REQUEST
- )
+ if isinstance(parsed_content, ImpactMeasurementPlan):
+ if parsed_content.activated:
+ return Response(
+ {"error": "Activate a measurement with its approval action."}, status=status.HTTP_400_BAD_REQUEST
+ )
+ try:
+ validate_authored_measurement_plan(parsed_content)
+ except ValueError as error:
+ return Response({"error": str(error)}, status=status.HTTP_400_BAD_REQUEST)
if isinstance(parsed_content, ChannelAssignment):
self._validate_channel_assignment(parsed_content, request)
with transaction.atomic():