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(signals): gate scout-authored report metrics on the org rollout (#102099)

posthog[bot]7be7b5fc2519
diff --git a/docs/internal/signals-report-metrics.md b/docs/internal/signals-report-metrics.md
index acfa35fe4c3f..b285d53cfd41 100644
--- a/docs/internal/signals-report-metrics.md
+++ b/docs/internal/signals-report-metrics.md
@@ -14,6 +14,8 @@ Metric refresh serves snapshots measured in the last 15 minutes from the query c
Use lowercase non-currency units such as `users`, `sessions`, or `failure`. Use uppercase ISO currency codes such as `USD`.
+Every write path reads the organization-level `signals-report-metrics` flag through `report_content_gates.py`. The agentic research pipeline and the scout `emit_report` / `edit_report` channel both drop authored metrics while the flag is off, because a stored definition is also a query that the refresh path runs later. The check fails closed, so a flag-service error stores no definitions. A scout that sends an empty list still clears the report's metrics.
+
## Access limits
Metrics with cohort references, including nested references, always hide both the query and the snapshot. This rule applies even when a token has all required scopes. `UserAccessControl` has no cohort object access policy, so the server cannot prove access. Keep this restriction until a safe cohort access policy exists. It is an intentional safety limit, not a display bug.
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index bae2e8272245..3d7fa4482593 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -485,7 +485,7 @@ An **append-only, attributed, schema-validated log of the work done on a report*
Scouts write them via `charts` on `emit_report` / `edit_report`. On an edit `charts` is the report's whole set — it replaces what was there, the way `summary` replaces the summary. Omitting the field (or sending null) leaves the existing charts alone; an explicit empty list clears them, so a scout can retract a chart its finding has outgrown rather than only ever swap one for another. On the emit path the safety judge sees a report's chart titles, captions, and queries alongside its prose, so an injected chart is suppressed with the report. The edit path judges nothing today — not title, summary, notes, reviewers, or charts — so a chart set by a later edit reaches the reader unscreened, exactly as an edited summary does.
-The main **agentic research pipeline** authors charts too, so every signal source that funnels through it (not just scouts) can produce a visual report. The research agent's presentation step (`report_generation/research.py`) returns `charts` alongside the title and summary; the caller activity (`temporal/agentic/report.py`) replaces `SignalReport.charts` with them, and a re-research is shown the report's current charts to keep, refresh, or drop. It is gated per team by the `signals-report-charts` flag (`_team_report_charts_enabled`, on in DEBUG) so it ships dark on the fleet-wide path. Unlike the scout emit path, these charts are **not** safety-judged: the pipeline judge screens the input signals before research runs, so it never sees research-authored charts — the same as it never sees the research-authored title/summary, which are agent output from already-screened signals.
+The main **agentic research pipeline** authors charts too, so every signal source that funnels through it (not just scouts) can produce a visual report. The research agent's presentation step (`report_generation/research.py`) returns `charts` alongside the title and summary; the caller activity (`temporal/agentic/report.py`) replaces `SignalReport.charts` with them, and a re-research is shown the report's current charts to keep, refresh, or drop. It is gated per team by the `signals-report-charts` flag (`team_report_charts_enabled` in `report_content_gates.py`, on in DEBUG) so it ships dark on the fleet-wide path. Unlike the scout emit path, these charts are **not** safety-judged: the pipeline judge screens the input signals before research runs, so it never sees research-authored charts — the same as it never sees the research-authored title/summary, which are agent output from already-screened signals.
**Report checks.** `SignalReportCheck` is the report's only forward-looking row: a title, a rationale, a kind-specific config, and the time to evaluate it. Everything else on a report describes what was already observed, so a claim that stopped holding was only ever found by a person going back to look. A check turns that into a scheduled measurement whose verdict lands in the artefact log as a `check_result`.
@@ -513,7 +513,7 @@ Snapshots are materialized without a requesting user under the team's default pr
Opening a report detail mounts every metric through the normal frontend Query path, so execution and caching follow the same query service used by insights. Consumers derive separate `BoldNumber` aggregate and `ActionsBar` longitudinal requests from each stored definition. If a query fails, the detail can show the latest cached snapshot instead. Longitudinal points remain in the analytics engine rather than being copied into a second time-series table.
-Agentic research writes metrics atomically with the matching title, summary, and charts. Its independent organization-level rollout uses `signals-report-metrics` (`_team_report_metrics_enabled`, on in DEBUG), rather than inheriting chart eligibility. While report metrics are enabled, the research output is the report's whole metric set: a nonempty list replaces the old set and an empty list clears it. Re-research receives the current set so it can repeat the metrics that remain valid. `None` is reserved for the feature-disabled or older-workflow replay path and preserves the stored set. Scouts set the initial whole set through `emit_report`. On `edit_report`, omitting `metrics` or sending null preserves the set, an empty list clears it, and a supplied list replaces it. A metrics-only edit changes Inbox content but does not redeliver the report to Slack.
+Agentic research writes metrics atomically with the matching title, summary, and charts. Its independent organization-level rollout uses `signals-report-metrics` (`team_report_metrics_enabled` in `report_content_gates.py`, on in DEBUG), rather than inheriting chart eligibility. While report metrics are enabled, the research output is the report's whole metric set: a nonempty list replaces the old set and an empty list clears it. Re-research receives the current set so it can repeat the metrics that remain valid. `None` is reserved for the feature-disabled or older-workflow replay path and preserves the stored set. Scouts set the initial whole set through `emit_report`. On `edit_report`, omitting `metrics` or sending null preserves the set, an empty list clears it, and a supplied list replaces it. Both scout write paths read the same rollout flag. While it is off, a supplied set is dropped before the safety judge, so nothing is stored and an edit preserves what the report holds. An empty list still clears. A metrics-only edit changes Inbox content but does not redeliver the report to Slack.
**Attribution.** Every write helper (`append_status` / `add_log` / `append_finding` / `append_dismissal`) requires an `ArtefactAttribution` — exactly one of `from_user(user_id)` / `from_task(task_id)` / `system()` — so no write site can silently skip it. Agent writes are attributed deterministically: sandbox provisioning bakes the agent's task id into an `X-PostHog-Task-Id` header on its MCP config, forwarded by the MCP server on every API call; the LLM never handles its own task id. The header is attribution metadata, not an authorization boundary (the token is team-scoped and the named task must belong to the same team).
diff --git a/products/signals/backend/report_content_gates.py b/products/signals/backend/report_content_gates.py
new file mode 100644
index 000000000000..2a538e70443b
--- /dev/null
+++ b/products/signals/backend/report_content_gates.py
@@ -0,0 +1,75 @@
+"""Organization-level rollout gates for the optional content a report carries.
+
+Charts and metrics roll out independently, so one flag cannot decide the other. The checks live in
+their own module rather than in `report_metrics.py`, which stays dependency-light because report
+models and Temporal payloads import it during process setup, and these checks need `Team` and the
+flag client.
+
+A metric gate binds every writer, not only the authoring agent: a stored metric definition is also a
+query that the refresh path runs later.
+"""
+
+from uuid import UUID
+
+from django.conf import settings
+
+import structlog
+
+from posthog.models.team.team import Team
+from posthog.ph_client import feature_enabled_or_false
+
+logger = structlog.get_logger(__name__)
+
+REPORT_CHARTS_FLAG = "signals-report-charts"
+REPORT_METRICS_FLAG = "signals-report-metrics"
+
+
+def _organization_flag_enabled(flag: str, organization_id: UUID) -> bool:
+ """Read one organization-keyed rollout flag.
+
+ The flag is evaluated for every call so a flip takes effect immediately, and is on in DEBUG for
+ local coverage. It fails closed, because a flag-service error must not add content to the reports
+ of an organization that is not opted in.
+ """
+ if settings.DEBUG:
+ return True
+ try:
+ return feature_enabled_or_false(
+ flag,
+ str(organization_id),
+ groups={"organization": str(organization_id)},
+ group_properties={"organization": {"id": str(organization_id)}},
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ logger.warning(
+ "signals report content flag check failed", flag=flag, organization_id=organization_id, exc_info=True
+ )
+ return False
+
+
+def _team_flag_enabled(flag: str, team_id: int) -> bool:
+ """The `team_id` adapter for callers that hold an id instead of a `Team`, such as a Temporal
+ activity input. Fails closed, so a team that cannot be read gets no report content."""
+ if settings.DEBUG:
+ return True
+ try:
+ organization_id = Team.objects.values_list("organization_id", flat=True).get(id=team_id)
+ except Exception:
+ logger.warning(
+ "signals report content flag check could not resolve the team", flag=flag, team_id=team_id, exc_info=True
+ )
+ return False
+ return _organization_flag_enabled(flag, organization_id)
+
+
+def organization_report_metrics_enabled(organization_id: UUID) -> bool:
+ return _organization_flag_enabled(REPORT_METRICS_FLAG, organization_id)
+
+
+def team_report_metrics_enabled(team_id: int) -> bool:
+ return _team_flag_enabled(REPORT_METRICS_FLAG, team_id)
+
+
+def team_report_charts_enabled(team_id: int) -> bool:
+ return _team_flag_enabled(REPORT_CHARTS_FLAG, team_id)
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.md
index af6abbd18889..64c1be75c7cc 100644
--- a/products/signals/backend/report_generation/AGENTS.md
+++ b/products/signals/backend/report_generation/AGENTS.md
@@ -70,7 +70,7 @@ The presentation step can also author `charts` — query nodes the inbox draws o
- **Expected on a data-shaped finding.** `_REPORT_CHARTS_GUIDANCE` tells the presentation step to attach the chart whenever the finding rests on data moving (a metric that broke, a rate that slid, a distribution that shifted), and to attach nothing when it lives in code, in a config, or in a single count. That pairs with the summary's 200-word target and 300-word ceiling: the chart carries the interval-by-interval series so the prose can state the finding and stop. Charts today correlate with longer summaries rather than shorter ones, because a run that attaches one still narrates the series underneath it, so the two rules only work together. Nothing but this guidance decides how many charts a report gets, so softening it back toward "usually the wrong call" is what returns the inbox to unillustrated walls of text.
- **A malformed chart costs the whole report.** `charts` rides in the same `ReportPresentationOutput` as the title and summary, and `MultiTurnSession._parse_and_validate` calls `model_validate` with no retry, so one bad node raises and the research run fails with nothing persisted. `_resolve_report_charts_payload` never sees it. That is why the guidance names the outer-node wrapping explicitly and tells the run to drop a doubtful chart rather than risk it. Giving a malformed chart its own degrade path would need a retry or a partial parse in the runner, which is shared with every other multi-turn caller.
-- **Opt-in.** Gated per team by the `signals-report-charts` flag (`_team_report_charts_enabled` in the caller activity; on in DEBUG). When off, both the chart guidance and the `charts` field itself are dropped from the presentation prompt (chart-free schema), and the caller drops anything the model returns anyway — so an un-opted team is never shown or steered toward charts on the delicate fleet-wide path.
+- **Opt-in.** Gated per team by the `signals-report-charts` flag (`team_report_charts_enabled` in `report_content_gates.py`; on in DEBUG). When off, both the chart guidance and the `charts` field itself are dropped from the presentation prompt (chart-free schema), and the caller drops anything the model returns anyway — so an un-opted team is never shown or steered toward charts on the delicate fleet-wide path.
- **Replace, not append.** `charts` is the report's whole set. On a re-research the previous charts are shown back as context (loaded from `SignalReport.charts` by `_load_previous_research`); the run keeps, refreshes, or drops them and the caller replaces the column with the result.
- **Persistence is atomic with the prose.** `run_agentic_report_activity` only _resolves_ the charts payload (`_resolve_report_charts_payload`) and returns it on `RunAgenticReportOutput.charts`; the column is written by the transition activity that also writes the title/summary (`mark_report_ready_activity` / `mark_report_pending_input_activity`), inside the same `transition_to` transaction. So charts and the prose they illustrate land together — a failed run or the not-actionable reset (neither writes the new prose) leaves the charts alone by construction, with no separate-transaction window. The resolver yields three outcomes: a valid non-empty set (replace the column); `None` when the team isn't opted in **or** the run authored no charts (leave the column alone — the presentation field is optional, so an omitted key and a deliberate "drop everything" both arrive empty and are indistinguishable, and wiping user-visible charts on that ambiguity is the worse failure, so the pipeline never auto-clears to zero; a human can clear from the inbox); and `[]` when the set busts the whole-set caps (clear, so a stale set can't sit under the new summary).
- **Not safety-judged.** The pipeline's safety judge screens the input signals before research runs, so it never sees research-authored charts — the same as it never sees research-authored title/summary. Charts are agent output derived from already-screened signals, consistent with that model. (This differs from the scout emit path, where charts and prose are judged together.)
@@ -84,7 +84,7 @@ The presentation step can also author up to six typed `metrics` alongside the pr
- **A malformed metric costs the whole report.** `metrics` rides in the same `ReportPresentationOutput` as the title and summary, and `MultiTurnSession._parse_and_validate` calls `model_validate` with no retry, so one rejected item fails the research run with nothing persisted. `_resolve_report_metrics_payload` never sees it, because `metric_batch_error` only checks whole-set rules (count, total query characters, duplicate ids, one primary, one affected-users). This is the same tradeoff as a malformed chart, on a wider surface: `ReportMetric` carries about fifteen field validators plus a cross-field one, against four on `ReportChart`, so a metric has many more ways to fail late. Giving one metric its own degrade path needs a retry or a partial parse in the runner, which is shared with every other multi-turn caller. Until then the `signals-report-metrics` flag bounds who is exposed, and the authoring guidance keeps the surface small by telling the run to omit a metric it cannot measure honestly.
- **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. 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.** Pipeline-authored metrics use the organization-level `signals-report-metrics` flag (`_team_report_metrics_enabled`, on in DEBUG), independent of `signals-report-charts`. When off, metric guidance and schema fields are removed and the caller preserves existing metrics. Scout-authored metrics are available independently and are safety-judged with the rest of the scout report.
+- **Independent opt-in.** Metrics use the organization-level `signals-report-metrics` flag (`report_content_gates.py`, on in DEBUG), independent of `signals-report-charts`. 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.
- **Replace, clear, or preserve as a set.** Metrics are the report's whole typed set. A valid non-empty pipeline result replaces them, an explicit or invalid enabled result clears them, and a disabled run returns `None` to preserve them. Scout edits use the same tri-state contract: omission preserves, `[]` clears, and a non-empty list replaces.
- **Persistence is atomic with prose.** The agentic activity returns the resolved metric payload on `RunAgenticReportOutput.metrics`; the ready or pending-input transition writes it in the same transaction as title and summary. There is no partially updated report state.
- **Design for more than user counts.** `kind`, `role`, format, unit, caption, and optional comparison support conversion, errors, latency, revenue, sessions, and occurrence metrics without overloading an affected-user field. `percentage` means percentage points while `percentage_scaled` means a 0–1 ratio, matching the two standard Trends axis formats. The schema still enforces at most one primary metric and at most one affected-users metric.
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index 8b55f9aef36a..0d388ddaab4d 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -57,6 +57,7 @@ from products.signals.backend.artefact_schemas import (
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalScoutRun
from products.signals.backend.repo_corrections import sanitized_repository
from products.signals.backend.report_charts import ChartSize, ReportChart, chart_batch_error
+from products.signals.backend.report_content_gates import organization_report_metrics_enabled
from products.signals.backend.report_generation.resolve_reviewers import (
ReviewerIdentitySet,
get_org_member_github_logins_by_user_uuid,
@@ -425,6 +426,23 @@ def _build_edit_metrics(metrics: list[ReportMetricInput] | None) -> list[ReportM
return _build_metrics(metrics)
+def _allowed_metrics(team: Team, metrics: list[ReportMetricInput] | None) -> list[ReportMetricInput] | None:
+ """Drop the authored metrics while the organization is not opted in to report metrics.
+
+ `None` is the answer because it is the shape both write paths already read as "this call names no
+ metrics", so the gate never disturbs the preserve/clear/replace contract. An empty list passes
+ through: it carries no definition to gate, and an organization that lost the flag must still be
+ able to take an old metric down.
+ """
+ if not metrics or organization_report_metrics_enabled(team.organization_id):
+ return metrics
+ logger.info(
+ "signals_scout: dropped report metrics because the organization is not opted in",
+ extra={"team_id": team.id, "count": len(metrics)},
+ )
+ return None
+
+
def _build_suggested_prompts(suggested_prompts: list[str] | None) -> list[str]:
"""Trim the scout's suggested prompts and refuse a set the report can't carry.
@@ -1372,7 +1390,9 @@ async def emit_report(
_assert_team_owns_run(team, run)
_validate_emit_inputs(title, summary, evidence)
chart_contents = _build_charts(charts)
- metric_contents = _build_metrics(metrics)
+ # Off the loop because the gate reads a feature flag, which can block on the flag service.
+ allowed_metrics = await database_sync_to_async(_allowed_metrics, thread_sensitive=False)(team, metrics)
+ metric_contents = _build_metrics(allowed_metrics)
prompt_contents = _build_suggested_prompts(suggested_prompts)
# Validate the explicit repository format up front (cheap, pure) so a malformed `owner/repo` fails
# before the safety-judge LLM call rather than after. Free-form selection still runs only if surfaced.
@@ -1523,7 +1543,7 @@ def emit_report_sync(
_assert_team_owns_run(team, run)
_validate_emit_inputs(title, summary, evidence)
chart_contents = _build_charts(charts)
- metric_contents = _build_metrics(metrics)
+ metric_contents = _build_metrics(_allowed_metrics(team, metrics))
prompt_contents = _build_suggested_prompts(suggested_prompts)
# Validate the explicit repository format up front (cheap, pure) so a malformed `owner/repo` fails
# before the safety-judge LLM call rather than after. Free-form selection still runs only if surfaced.
@@ -2094,7 +2114,9 @@ async def edit_report(
built_evidence = _build_signals(append_evidence) if append_evidence else None
built_charts = _build_edit_charts(charts)
built_prompts = _build_edit_suggested_prompts(suggested_prompts)
- built_metrics = _build_edit_metrics(metrics)
+ # Off the loop because the gate reads a feature flag, which can block on the flag service.
+ allowed_metrics = await database_sync_to_async(_allowed_metrics, thread_sensitive=False)(team, metrics)
+ built_metrics = _build_edit_metrics(allowed_metrics)
# Gates before the judge, mirroring emit: a disabled or dry-run scout must not spend an LLM call.
await database_sync_to_async(_assert_edit_gates, thread_sensitive=False)(
team, run, report_id, len(built_evidence or [])
@@ -2142,7 +2164,8 @@ async def edit_report(
suggested_reviewers=suggested_reviewers,
repository=normalized_repository,
charts=charts,
- metrics=metrics,
+ # The gated set, so the event reports what the edit wrote rather than what the scout asked for.
+ metrics=allowed_metrics,
suggested_prompts=suggested_prompts,
)
await _forward_report_event_async(team, forward)
@@ -2183,7 +2206,8 @@ def edit_report_sync(
built_evidence = _build_signals(append_evidence) if append_evidence else None
built_charts = _build_edit_charts(charts)
built_prompts = _build_edit_suggested_prompts(suggested_prompts)
- built_metrics = _build_edit_metrics(metrics)
+ allowed_metrics = _allowed_metrics(team, metrics)
+ built_metrics = _build_edit_metrics(allowed_metrics)
# Gates before the judge, mirroring emit: a disabled or dry-run scout must not spend an LLM call.
_assert_edit_gates(team, run, report_id, len(built_evidence or []))
# Reviewers resolve before the judge too: resolution is the one step that rejects caller input
@@ -2227,7 +2251,8 @@ def edit_report_sync(
suggested_reviewers=suggested_reviewers,
repository=normalized_repository,
charts=charts,
- metrics=metrics,
+ # The gated set, so the event reports what the edit wrote rather than what the scout asked for.
+ metrics=allowed_metrics,
suggested_prompts=suggested_prompts,
)
if forward is not None:
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index c1257b93f9cb..5fb24a9c2598 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -2,7 +2,6 @@ from dataclasses import dataclass
from datetime import datetime
from typing import Any, TypeVar
-from django.conf import settings
from django.db import transaction
from django.db.models import Q
@@ -14,7 +13,6 @@ from pydantic import BaseModel, ValidationError
from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.models.team.team import Team
-from posthog.ph_client import feature_enabled_or_false
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.scoped import scoped_temporal
@@ -28,6 +26,7 @@ from products.signals.backend.auto_start import ReviewerContent
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
from products.signals.backend.repo_corrections import SCOUT_REPOSITORY_CONTENT_NEEDLE, WRONG_REPO_CONTENT_NEEDLE
from products.signals.backend.report_charts import ReportChart, chart_batch_error
+from products.signals.backend.report_content_gates import team_report_charts_enabled, team_report_metrics_enabled
from products.signals.backend.report_generation.research import (
ActionabilityAssessment,
ActionabilityChoice,
@@ -591,52 +590,6 @@ def _team_has_business_knowledge(team_id: int) -> bool:
return False
-def _team_report_charts_enabled(team_id: int) -> bool:
- """Whether the research agent may attach charts to this team's reports.
-
- Gated by the `signals-report-charts` flag, org-keyed, evaluated fresh per run so a flip takes
- effect immediately. Off by default everywhere so this ships dark on the fleet-wide research path;
- on locally so `analyze_report` exercises it. Fails closed to False — a flag-service hiccup must
- not add charts to reports for a team that isn't opted in."""
- if settings.DEBUG:
- return True
- try:
- team = Team.objects.get(id=team_id)
- return feature_enabled_or_false(
- "signals-report-charts",
- str(team.organization_id),
- groups={"organization": str(team.organization_id)},
- group_properties={"organization": {"id": str(team.organization_id)}},
- send_feature_flag_events=False,
- )
- except Exception:
- logger.warning("report-charts availability check failed", team_id=team_id, exc_info=True)
- return False
-
-
-def _team_report_metrics_enabled(team_id: int) -> bool:
- """Whether the research agent may author impact metrics for this team's reports.
-
- Metrics have their own organization-level rollout so a team's chart rollout cannot accidentally
- decide whether the main report pipeline measures user impact. The flag is evaluated for every
- run, is on in DEBUG for local coverage, and fails closed on flag-service errors.
- """
- if settings.DEBUG:
- return True
- try:
- team = Team.objects.get(id=team_id)
- return feature_enabled_or_false(
- "signals-report-metrics",
- str(team.organization_id),
- groups={"organization": str(team.organization_id)},
- group_properties={"organization": {"id": str(team.organization_id)}},
- send_feature_flag_events=False,
- )
- except Exception:
- logger.warning("report-metrics availability check failed", team_id=team_id, exc_info=True)
- return False
-
-
# The posture the research sandbox's token is minted from. Named once because two things depend on
# it: the token the sandbox holds, and the memory protocol rendered into the research prompt. The
# prompt side derives its gate from this constant, so a posture that loses the scratchpad write
@@ -713,10 +666,10 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
service_tier=agent_runtime.service_tier,
)
has_bk = await database_sync_to_async(_team_has_business_knowledge, thread_sensitive=False)(input.team_id)
- charts_enabled = await database_sync_to_async(_team_report_charts_enabled, thread_sensitive=False)(
+ charts_enabled = await database_sync_to_async(team_report_charts_enabled, thread_sensitive=False)(
input.team_id
)
- metrics_enabled = await database_sync_to_async(_team_report_metrics_enabled, thread_sensitive=False)(
+ metrics_enabled = await database_sync_to_async(team_report_metrics_enabled, thread_sensitive=False)(
input.team_id
)
# 2. Load previous research if this is a re-promoted report
diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.py
index 2e8175d75b8f..91d4d60c593e 100644
--- a/products/signals/backend/test/test_agentic_report_activity.py
+++ b/products/signals/backend/test/test_agentic_report_activity.py
@@ -201,11 +201,11 @@ async def _run_activity_with_output(
lambda team_id: 1,
)
monkeypatch.setattr(
- "products.signals.backend.temporal.agentic.report._team_report_charts_enabled",
+ "products.signals.backend.temporal.agentic.report.team_report_charts_enabled",
lambda team_id: charts_enabled,
)
monkeypatch.setattr(
- "products.signals.backend.temporal.agentic.report._team_report_metrics_enabled",
+ "products.signals.backend.temporal.agentic.report.team_report_metrics_enabled",
lambda team_id: metrics_enabled,
)
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 5bab676ca539..8e467e10328c 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -1,4 +1,5 @@
import json
+from typing import Any
from uuid import uuid4
import pytest
@@ -53,6 +54,7 @@ EMBED_PATH = "products.signals.backend.scout_report.persistence.emit_embedding_r
# Patched at its source module so the lazy import inside `_maybe_autostart_report` picks up the mock.
AUTOSTART_PATH = "products.signals.backend.auto_start.maybe_autostart_from_report_artefacts"
CAPTURE_PATH = "products.signals.backend.scout_harness.tools.report.posthoganalytics.capture"
+METRICS_GATE_PATH = "products.signals.backend.scout_harness.tools.report.organization_report_metrics_enabled"
# The customer-facing copy lands in the scout's own team project via capture_internal (a network boundary).
CAPTURE_INTERNAL_PATH = "products.signals.backend.scout_harness.tools.report.capture_internal"
CONNECTED_REPOS_PATH = "products.signals.backend.scout_harness.tools.report._connected_repositories"
@@ -92,6 +94,10 @@ class TestScoutReportAPI(APIBaseTest):
# Keep it inert by default so emit/edit tests don't hit the network; the two dedicated tests
# assert against this mock.
self.capture_internal_mock = patch(CAPTURE_INTERNAL_PATH).start()
+ # Report metrics ship behind an organization-level flag that is off outside DEBUG. Opt this
+ # organization in, so the metric cases assert the contract rather than the rollout; the two
+ # gate tests below turn it back off.
+ self.metrics_enabled_mock = patch(METRICS_GATE_PATH, return_value=True).start()
self.addCleanup(patch.stopall)
def _emit_url(self, run_id: str) -> str:
@@ -1651,29 +1657,48 @@ class TestScoutReportAPI(APIBaseTest):
@parameterized.expand(
[
- ("omitted", {}, 1, None),
- ("null", {"metrics": None}, 1, None),
- ("empty_list", {"metrics": []}, 0, 0),
+ ("omitted", True, "omit", ["affected-users"], None),
+ ("null", True, "null", ["affected-users"], None),
+ ("replace", True, "replace", ["replacement"], 1),
+ ("empty_list", True, "clear", [], 0),
+ # While the organization is not opted in, a supplied set is dropped, so the report keeps
+ # the metric it holds. A clear carries no definition to gate, so it still lands.
+ ("not_opted_in_replace", False, "replace", ["affected-users"], None),
+ ("not_opted_in_clear", False, "clear", [], 0),
]
)
- def test_edit_metrics_distinguishes_untouched_from_cleared(
- self, _name: str, metric_field: dict, expected_stored: int, expected_metrics_set: int | None
+ def test_edit_metrics_distinguishes_untouched_replaced_and_cleared(
+ self,
+ _name: str,
+ opted_in: bool,
+ instruction: str,
+ expected_stored: list[str],
+ expected_metrics_set: int | None,
) -> None:
run = _make_run(self.team)
- metric = self._affected_users_metric()
+ instructions: dict[str, dict[str, Any]] = {
+ "omit": {},
+ "null": {"metrics": None},
+ "clear": {"metrics": []},
+ "replace": {"metrics": [{**self._affected_users_metric(), "metric_id": "replacement"}]},
+ }
with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()), patch(CAPTURE_PATH):
created = self.client.post(
- self._emit_url(str(run.id)), data=self._payload(metrics=[metric]), format="json"
+ self._emit_url(str(run.id)),
+ data=self._payload(metrics=[self._affected_users_metric()]),
+ format="json",
).json()
+ self.metrics_enabled_mock.return_value = opted_in
response = self.client.post(
self._edit_url(str(run.id)),
- data={"report_id": created["report_id"], "append_note": "checked", **metric_field},
+ data={"report_id": created["report_id"], "append_note": "checked", **instructions[instruction]},
format="json",
)
assert response.status_code == status.HTTP_200_OK, response.json()
assert response.json()["metrics_set"] == expected_metrics_set
- assert len(SignalReport.objects.get(id=created["report_id"]).metrics) == expected_stored
+ stored = SignalReport.objects.get(id=created["report_id"]).metrics
+ assert [entry["metric_id"] for entry in stored] == expected_stored
def test_clearing_metrics_is_a_valid_sole_edit(self) -> None:
run = _make_run(self.team)
@@ -1693,6 +1718,23 @@ class TestScoutReportAPI(APIBaseTest):
assert response.json()["metrics_set"] == 0
assert SignalReport.objects.get(id=created["report_id"]).metrics == []
+ def test_emit_stores_no_metrics_while_the_organization_is_not_opted_in(self) -> None:
+ # The report still surfaces; only the metrics drop. Without the gate an organization whose
+ # Inbox hides metrics accumulates metric definitions, and the refresh queries behind them.
+ run = _make_run(self.team)
+ self.metrics_enabled_mock.return_value = False
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()), patch(CAPTURE_PATH):
+ response = self.client.post(
+ self._emit_url(str(run.id)),
+ data=self._payload(metrics=[self._affected_users_metric()]),
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["emitted"] is True
+ assert SignalReport.objects.get(id=body["report_id"], team=self.team).metrics == []
+
def test_suggested_prompt_edit_event_uuid_keys_on_the_prompts(self) -> None:
# Same collision class as the chart case above: suggested prompts are a valid sole input to an
# edit, so two prompt-only edits to one report in a run share every other part of the key.