: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(signals): reframe the chart prompts around charting (#100323)
posthog[bot]8d3947dab33c
diff --git a/products/signals/backend/report_charts.py b/products/signals/backend/report_charts.pyindex b683115e2c09..a873700f67cc 100644--- a/products/signals/backend/report_charts.py+++ b/products/signals/backend/report_charts.py@@ -48,6 +48,14 @@ MAX_CHART_CAPTION_LENGTH = 500ChartSize = Literal["small", "medium", "large"]CHART_SIZES: tuple[ChartSize, ...] = ("small", "medium", "large")+# When to attach a chart, as both chart prompts state it: the scout channel's `_REPORT_CHARTS` and+# the research pipeline's `_REPORT_CHARTS_GUIDANCE`. Shared rather than written twice because the+# two drifted apart once already, and each talked its readers out of charting in its own words. The+# prose is channel-agnostic on purpose — it names no tool — so each prompt appends its own mechanics.+WHEN_TO_CHART = """**When the finding rests on data moving, attach the chart that shows it.** A metric that broke, a rate that slid, a distribution that shifted, a funnel step that collapsed: each of those is a shape, and a reader takes a shape in at a glance where a paragraph of figures makes them rebuild it in their head. The test is the result you got back, never the tool you got it from: a query that returned a series over time, a distribution across buckets, or a set of funnel steps has a shape to draw, and the same tool returning one aggregate row does not. Attaching is what keeps the prose short, because the summary can state the finding and leave the detail to the picture.++Attach nothing when there is no shape to show. A finding that lives entirely in code, in a config, or in a single count has nothing to draw, and a chart restating one number the summary already gives is noise, so write the number instead. One or two charts is the usual answer for a data-shaped report, and none for the rest."""+# Bounds the JSON a single chart can carry into the report and, from there, into the safety-judge# prompt. Generous next to a real query node; small enough that a malformed one can't blow up a call._MAX_CHART_QUERY_CHARS = 20_000diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.pyindex b584fcfa2e30..766f9d1c769d 100644--- a/products/signals/backend/report_generation/research.py+++ b/products/signals/backend/report_generation/research.py@@ -5,7 +5,7 @@ import asyncioimport loggingfrom typing import TYPE_CHECKING-from pydantic import BaseModel, Field, field_validator, model_validator+from pydantic import BaseModel, Field, ValidationError, field_validator, model_validator# Canonical homes of the judgment/finding shapes are the artefact content schemas (they are# persisted as artefacts); re-exported here because this module is where research callers and@@ -22,7 +22,7 @@ from products.signals.backend.artefact_schemas import (# `posthog.schema` onto the research path.from products.signals.backend.pipeline_identity import AI_STAGE_RESEARCHfrom products.signals.backend.report_actionability import ACTIONABILITY_CRITERIA-from products.signals.backend.report_charts import MAX_REPORT_CHARTS, ReportChart+from products.signals.backend.report_charts import MAX_REPORT_CHARTS, WHEN_TO_CHART, ReportChartfrom products.signals.backend.report_metrics import (DEFAULT_LIVE_METRIC_DATE_FROM,MAX_LIVE_METRIC_QUERY_POINTS,@@ -60,6 +60,15 @@ __all__ = [# TODO: Signals deduplication step before the research+def _rejection_reason(error: Exception) -> str:+ """Why a chart was rejected, as failing field and rule only — never the rejected content."""+ if not isinstance(error, ValidationError):+ return type(error).__name__+ return ", ".join(+ f"{'.'.join(str(part) for part in entry['loc']) or 'chart'}: {entry['type']}" for entry in error.errors()+ )++class ReportPresentationOutput(BaseModel):title: str = Field(description="""@@ -120,6 +129,28 @@ Hard rules:),)+ @field_validator("charts", mode="before")+ @classmethod+ def drop_charts_that_do_not_validate(cls, v: object) -> object:+ # Title, summary, and charts arrive as one response, so a single malformed node used to fail+ # the whole presentation step and end the run with no report at all. Validating each entry+ # here keeps the cost of a bad chart to that chart: it is dropped, the prose still lands,+ # and the prompt can ask for charts without hedging against the response failing.+ if not isinstance(v, list):+ return v+ kept: list[ReportChart] = []+ for index, entry in enumerate(v):+ try:+ kept.append(ReportChart.model_validate(entry))+ except Exception as e:+ # Report the failing fields and rules, never the error itself: pydantic renders the+ # rejected `input_value`, which would copy the chart's query — HogQL text and filter+ # values — into application logs.+ logger.warning(+ "presentation: dropped chart at index %d that did not validate (%s)", index, _rejection_reason(e)+ )+ return kept+@field_validator("title", "summary")@classmethoddef fields_must_not_be_empty(cls, v: str) -> str:@@ -375,13 +406,11 @@ def _render_previous_presentation_context(previous_title: str | None, previous_s# team that isn't opted in is never shown or steered toward charts on the delicate fleet-wide path._REPORT_CHARTS_GUIDANCE = f"""## Attaching charts-You may attach charts under `charts`, which the inbox draws on the report itself so a data move is visible next to the sentence describing it rather than a number the reader has to go and reproduce.--**When the finding rests on data moving, attach the chart that shows it.** A metric that broke, a rate that slid, a distribution that shifted, a funnel step that collapsed: each of those is a shape, and a reader takes a shape in at a glance where a paragraph of figures makes them rebuild it in their head. The test is the result you got back, never the tool you got it from: a query that returned a series over time, a distribution across buckets, or a set of funnel steps has a shape to draw, and the same tool returning one aggregate row does not. Attaching is what keeps the prose short, because the summary can state the finding and leave the detail to the picture.+`charts` carries queries the inbox draws on the report itself, so a data move is visible next to the sentence describing it rather than a number the reader has to go and reproduce.-Attach nothing when there is no shape to show. A finding that lives entirely in code, in a config, or in a single count has nothing to draw, and a chart restating one number the summary already gives is noise, so write the number instead. One or two charts is the usual answer for a data-shaped report, and none for the rest.+{WHEN_TO_CHART}-- **Each chart is `chart_id` + `title` + `query`.** `chart_id` is your own slug (lowercase letters, numbers, `_`, `-`); `title` is the heading above it; `query` is a query node — `InsightVizNode` (an ad-hoc product-analytics chart), `DataVisualizationNode` (a `HogQLQuery` source, plus `display` and `chartSettings` for a graph rather than a result table), or `SavedInsightNode` (an existing insight by `shortId`). Any other kind is refused. `query` is that outer node, never the bare query you ran: a `TrendsQuery` goes inside `InsightVizNode.source` and a `HogQLQuery` inside `DataVisualizationNode.source`. Getting that wrong costs more than the chart, because the title, the summary, and the charts are validated as one response, so a malformed node fails the whole thing and the research run ends with no report. When in doubt about a chart, leave it out and keep the prose. Add a `caption` when there's a specific thing to look at.+- **Each chart is `chart_id` + `title` + `query`.** `chart_id` is your own slug (lowercase letters, numbers, `_`, `-`); `title` is the heading above it; `query` is a query node — `InsightVizNode` (an ad-hoc product-analytics chart), `DataVisualizationNode` (a `HogQLQuery` source, plus `display` and `chartSettings` for a graph rather than a result table), or `SavedInsightNode` (an existing insight by `shortId`). Any other kind is refused. `query` is that outer node, never the bare query you ran: a `TrendsQuery` goes inside `InsightVizNode.source` and a `HogQLQuery` inside `DataVisualizationNode.source`. A chart whose node is malformed is dropped on its own and the rest of the report still lands, so a chart you are unsure about costs you that chart and nothing else. Add a `caption` when there's a specific thing to look at.- **A graph from SQL needs its axes named.** Setting `display` on a `DataVisualizationNode` without `chartSettings` draws every row at one x position instead of a series: `chartSettings.xAxis.column` and `chartSettings.yAxis[].column` say which columns of your result are which, naming them exactly as your `SELECT` aliases them. A daily count aliased `SELECT toDate(timestamp) AS day, count() AS occurrences` needs `"chartSettings": {{"xAxis": {{"column": "day"}}, "yAxis": [{{"column": "occurrences"}}]}}`. Leave `display` off entirely and the node renders the result table instead, which reads better than a chart for a handful of rows.- **Only attach a query you actually ran this session.** A well-formed node of an allowed kind holding a broken query is stored without complaint and then fails to draw when the reader opens the report, with nothing to tell you. So build each chart from a query you already executed through `mcp__posthog__exec` (`call query-trends {{...}}`, `call execute-sql {{...}}`, or read the exact node off an existing insight) – never one written from memory.- **A chart renders data, it does not run code.** HogVM `bytecode`, a nested `HogQuery`, `sendRawQuery`, and a nested `SuggestedQuestionsQuery` are each refused wherever they sit in the node. A warehouse query is fine through HogQL — keep `connectionId`, drop `sendRawQuery`.diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex ce1b17049795..a8a3fb544f90 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -10,7 +10,7 @@ from typing import TYPE_CHECKINGfrom pydantic import BaseModel, Fieldfrom products.signals.backend.report_actionability import ACTIONABILITY_CRITERIA-from products.signals.backend.report_charts import MAX_REPORT_CHARTS+from products.signals.backend.report_charts import MAX_REPORT_CHARTS, WHEN_TO_CHARTfrom products.signals.backend.report_metrics import (DEFAULT_LIVE_METRIC_DATE_FROM,MAX_LIVE_METRIC_QUERY_POINTS,@@ -76,6 +76,7 @@ _RENDERED_IMPORTS: dict[str, object] = {"MAX_REPORT_METRICS": MAX_REPORT_METRICS,"MAX_SUGGESTED_PROMPTS": MAX_SUGGESTED_PROMPTS,"MAX_SUGGESTED_PROMPT_LENGTH": MAX_SUGGESTED_PROMPT_LENGTH,+ "WHEN_TO_CHART": WHEN_TO_CHART,}@@ -230,19 +231,25 @@ _REPORT_STEPS_BOTH = """4. **Search the inbox before you author.** A report you'- **Edit** an existing report (`scout-edit-report`) when one already covers it. This is the default when a match exists.- **Author** a fresh report (`scout-emit-report`) only when nothing in the inbox covers it, or a known issue has new evidence that changes the verdict. Set `suggested_reviewers` (see *Suggested reviewers route the report*).- **Remember** a learning so you don't redo this work next run (call `scout-scratchpad-remember`).- - **Skip** with a one-line note in your final summary."""+ - **Skip** with a one-line note in your final summary.++ Whenever what you write rests on data moving, attach the chart that shows it (see *Attaching charts*)."""_REPORT_STEPS_EMIT_ONLY = """4. **Search the inbox before you author.** A report you'd write may already exist. ALWAYS check first (see *Authoring reports: search the inbox first*). This run can author but not edit, so when a report already covers the issue, record a scratchpad note and move on rather than authoring a near-duplicate.5. **Author or skip.** For each issue worth surfacing, decide whether to:- **Author** a fresh report (`scout-emit-report`) when nothing in the inbox covers it. Set `suggested_reviewers` (see *Suggested reviewers route the report*).- **Remember** a learning so you don't redo this work next run (call `scout-scratchpad-remember`).- - **Skip** with a one-line note in your final summary."""+ - **Skip** with a one-line note in your final summary.++ Whenever what you write rests on data moving, attach the chart that shows it (see *Attaching charts*)."""_REPORT_STEPS_EDIT_ONLY = """4. **Find the report to update.** Locate the report your evidence bears on (see *Editing existing reports*). This run can update existing reports but cannot author new ones.5. **Edit or skip.** For each issue worth surfacing, decide whether to:- **Edit** the existing report (`scout-edit-report`): use `append_evidence` for a fresh observation, or `append_note` for commentary.- **Remember** a learning so you don't redo this work next run (call `scout-scratchpad-remember`).- - **Skip** with a one-line note in your final summary, including when nothing in the inbox matches and there's therefore nothing to update."""+ - **Skip** with a one-line note in your final summary, including when nothing in the inbox matches and there's therefore nothing to update.++ Whenever what you write rests on data moving, attach the chart that shows it (see *Attaching charts*)."""_SCRATCHPAD_KEYS = """# Scratchpad keys@@ -594,6 +601,7 @@ A report you author renders in the inbox like any pipeline report: `title` is th- **Summary:** front-load the verdict and structure the body per *Writing the summary* below.- **Style:** write the title and summary in Simplified Technical English, following the `writing-simplified-technical-english` skill: one meaning per word, active voice, simple tenses, one idea per sentence.- **Evidence:** concrete observations (`description` + a stable `source_id`). These are the report's backbone and what the safety judge, and any later research, reasons over. At least one is required.+- **Charts:** when the finding rests on data moving, attach the chart that shows it and place it from the summary, per *Attaching charts* below.- **Actionability:** set `actionability` honestly, against the criteria below. `immediately_actionable` surfaces as READY, `requires_human_input` as PENDING_INPUT, `not_actionable` is suppressed. The safety judge can suppress regardless, so don't inflate it.- **Already addressed:** set `already_addressed` when the fix has landed *or* is already in flight: an open pull request, a recently active branch, or an assigned / in-progress issue or agent task covering the same problem. An immediately-actionable report can open a draft PR on its own, so leaving this `false` on work someone already has going produces a competing PR the team has to throw away. Say what you found in `actionability_explanation` and keep filing the report: a team wants to know the issue is real and being handled, it just must not be worked twice.@@ -630,7 +638,9 @@ _REPORT_METRICS = f"""# Measuring report impact_REPORT_CHARTS = f"""# Attaching charts-`charts` on the report tools carries queries the inbox draws on the report itself, so a move is visible next to the sentence describing it instead of being a number the reader has to reproduce. Optional, and worth it only when the shape of the data is the point: a trend that broke, a distribution that shifted, a funnel step that collapsed. A chart restating one number the summary already gives is noise, so write the number.+`charts` on the report tools carries queries the inbox draws on the report itself, so a move is visible next to the sentence describing it instead of being a number the reader has to reproduce.++{WHEN_TO_CHART}- **Each chart is `chart_id` + `title` + `query`.** `chart_id` is your own slug (lowercase letters, numbers, `_`, `-`), `title` the heading above it, `query` a query node: `InsightVizNode` (an ad-hoc product analytics chart), `DataVisualizationNode` (a `HogQLQuery` source, plus `display` and `chartSettings` when you want a graph rather than a result table), or `SavedInsightNode` (an existing insight by `shortId`). Anything else is refused. Add a `caption` when there's something specific to look at.- **A graph from SQL needs its axes named.** Setting `display` without `chartSettings` draws an empty box: `chartSettings.xAxis.column` and `chartSettings.yAxis[].column` say which columns of your result are which. Leave `display` off entirely and the node renders the result table instead, which reads better than a chart for a handful of rows.diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.pyindex de850a0984a4..af7d65396f80 100644--- a/products/signals/backend/temporal/agentic/report.py+++ b/products/signals/backend/temporal/agentic/report.py@@ -90,6 +90,10 @@ class RunAgenticReportOutput:# Resolved impact-metric payload, with the same replay-safe replace/clear/preserve semantics as# charts. The transition activity writes it with the matching title and summary.metrics: list[dict[str, Any]] | None = None+ # Whether the rollout let this run author charts at all. Carried so telemetry can tell a run+ # that chose not to chart apart from one that was never allowed to, which would otherwise read+ # as the agent's charting rate moving on every rollout step. `None` predates the field.+ charts_enabled: bool | None = None_ArtefactContentT = TypeVar("_ArtefactContentT", bound=BaseModel)@@ -775,6 +779,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgentirepository=repository,charts=charts_payload,metrics=metrics_payload,+ charts_enabled=charts_enabled,)except Exception as error:logger.exception(diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex 6185bbbf204c..14a775c20cb3 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -85,6 +85,8 @@ def _capture_report_event(result: str | None = None,failure_reason: str | None = None,pending_reason: str | None = None,+ chart_count: int | None = None,+ charts_enabled: bool | None = None,) -> None:properties: dict = {"report_id": report_id,@@ -94,6 +96,16 @@ def _capture_report_event(}if result is not None:properties["result"] = result+ # Only the two outcomes that write prose carry a chart set, so the property is absent rather+ # than zero on the others — a `failed` run charting nothing is not the same observation as a+ # report that landed without a chart. The count is the report's stored set after the+ # transition, which a run that authored nothing leaves standing from the run before it.+ if chart_count is not None:+ properties["chart_count"] = chart_count+ # Chart rate is only readable within the population that could chart, so the rollout state this+ # run saw rides along with the count. Absent when no research ran to ask.+ if charts_enabled is not None:+ properties["charts_enabled"] = charts_enabledif failure_reason is not None:properties["failure_reason"] = failure_reasonif pending_reason is not None:@@ -131,6 +143,9 @@ class ReportDecision:charts: list[dict[str, Any]] | None = None# Resolved metric payload with the same preserve/replace/clear semantics as charts.metrics: list[dict[str, Any]] | None = None+ # The chart rollout state the research run saw (see `RunAgenticReportOutput.charts_enabled`).+ # `None` for the no-repo branch, which does no research and so never asks.+ charts_enabled: bool | None = None# Suggested prompts to store with the title/summary. Always `[]`, because every decision carries# a freshly written title and summary, and the pipeline does not author prompts yet: whatever a# scout suggested was written against the prose this decision replaces, so leaving it would put@@ -433,6 +448,7 @@ class SignalReportSummaryWorkflow:explanation=agentic_result.explanation,charts=agentic_result.charts,metrics=agentic_result.metrics,+ charts_enabled=agentic_result.charts_enabled,pending_reason="agent_requested",)if decision.choice == ActionabilityChoice.NOT_ACTIONABLE:@@ -472,6 +488,7 @@ class SignalReportSummaryWorkflow:charts=decision.charts,metrics=decision.metrics,suggested_prompts=decision.suggested_prompts,+ charts_enabled=decision.charts_enabled,pending_reason=decision.pending_reason,),start_to_close_timeout=timedelta(minutes=1),@@ -493,6 +510,7 @@ class SignalReportSummaryWorkflow:charts=decision.charts,metrics=decision.metrics,suggested_prompts=decision.suggested_prompts,+ charts_enabled=decision.charts_enabled,),start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=3),@@ -763,6 +781,20 @@ async def mark_report_in_progress_activity(input: MarkReportInProgressInput) ->)+@frozen+class _ReportTransition:+ """What a status-transition activity learned inside its transaction, for its telemetry to read.++ `has_new_signals` only means anything on the ready transition, so it defaults to False for the+ others. On a duplicate transition the activity returns before reading the counts.+ """++ run_count: int+ chart_count: int+ was_duplicate: bool+ has_new_signals: bool = False++@frozenclass MarkReportReadyInput:team_id: int@@ -781,6 +813,8 @@ class MarkReportReadyInput:# default. The research pipeline passes `[]`: it doesn't author prompts yet, and the ones a# scout wrote were written against the summary this transition is replacing.suggested_prompts: list[str] | None = None+ # The chart rollout state the research run saw, for the completion event. Not persisted.+ charts_enabled: bool | None = None@temporalio.activity.defn@@ -791,13 +825,15 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:try:@transaction.atomic- def do_update() -> tuple[bool, int, bool]:+ def do_update() -> _ReportTransition:report = SignalReport.objects.select_for_update().get(id=input.report_id, team_id=input.team_id)if report.status == SignalReport.Status.READY:- return False, report.run_count, True+ return _ReportTransition(run_count=report.run_count, chart_count=0, was_duplicate=True)if report.status == SignalReport.Status.CANDIDATE:# Previous attempt took the re-promotion branch; preserve has_new_signals=True.- return True, report.run_count, True+ return _ReportTransition(+ run_count=report.run_count, chart_count=0, was_duplicate=True, has_new_signals=True+ )updated_fields = report.transition_to(SignalReport.Status.READY, title=input.title, summary=input.summary)# The pass is only now known to have covered anything, so this is where the count the# bucket schedule reads is written. A run that failed or paused earlier leaves the@@ -826,9 +862,14 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:# re-promote it back to candidate and loop to also process new signalscandidate_fields = report.transition_to(SignalReport.Status.CANDIDATE)report.save(update_fields=candidate_fields)- return has_new_signals, report.run_count, False+ return _ReportTransition(+ run_count=report.run_count,+ chart_count=len(report.charts or []),+ was_duplicate=False,+ has_new_signals=has_new_signals,+ )- has_new_signals, run_count, was_already_done = await database_sync_to_async(do_update, thread_sensitive=False)()+ transition = await database_sync_to_async(do_update, thread_sensitive=False)()except Exception as e:logger.exception(f"Failed to mark report {input.report_id} as ready: {e}",@@ -836,13 +877,13 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:)raise- if was_already_done:+ if transition.was_duplicate:logger.info(f"Report {input.report_id} already past ready transition, skipping duplicate",report_id=input.report_id,- has_new_signals=has_new_signals,+ has_new_signals=transition.has_new_signals,)- return has_new_signals+ return transition.has_new_signalsteam = await Team.objects.select_related("organization").aget(pk=input.team_id)_capture_report_event(@@ -851,17 +892,19 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:organization=team.organization,report_id=input.report_id,signal_count=input.processed_signal_count,- run_count=run_count,+ run_count=transition.run_count,source_products=input.source_products,result="ready",+ chart_count=transition.chart_count,+ charts_enabled=input.charts_enabled,)logger.debug(f"Marked report {input.report_id} as ready",report_id=input.report_id,title=input.title,- has_new_signals=has_new_signals,+ has_new_signals=transition.has_new_signals,)- return has_new_signals+ return transition.has_new_signals@frozen@@ -1008,6 +1051,8 @@ class MarkReportPendingInput:metrics: list[dict[str, Any]] | None = None# See MarkReportReadyInput.suggested_prompts — same transaction, same three states.suggested_prompts: list[str] | None = None+ # See MarkReportReadyInput.charts_enabled — reported, never stored.+ charts_enabled: bool | None = None# Coarse cause of the transition ("repo_selection_required" / "agent_requested"), see# ReportDecision.pending_reason.pending_reason: str | None = None@@ -1021,10 +1066,10 @@ async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> Ntry:@transaction.atomic- def do_update() -> tuple[int, bool]:+ def do_update() -> _ReportTransition:report = SignalReport.objects.select_for_update().get(id=input.report_id, team_id=input.team_id)if report.status == SignalReport.Status.PENDING_INPUT:- return report.run_count, True+ return _ReportTransition(run_count=report.run_count, chart_count=0, was_duplicate=True)updated_fields = report.transition_to(SignalReport.Status.PENDING_INPUT, title=input.title, summary=input.summary, error=input.reason)@@ -1041,9 +1086,11 @@ async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> N# transaction) — not a model field, so it never persists past this save.report._pending_reason = input.pending_reason # type: ignore[attr-defined]report.save(update_fields=updated_fields)- return report.run_count, False+ return _ReportTransition(+ run_count=report.run_count, chart_count=len(report.charts or []), was_duplicate=False+ )- run_count, was_already_pending_input = await database_sync_to_async(do_update, thread_sensitive=False)()+ transition = await database_sync_to_async(do_update, thread_sensitive=False)()except Exception as e:logger.exception(f"Failed to mark report {input.report_id} as pending_input: {e}",@@ -1051,7 +1098,7 @@ async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> N)raise- if was_already_pending_input:+ if transition.was_duplicate:logger.info(f"Report {input.report_id} already in pending_input status, skipping duplicate transition",report_id=input.report_id,@@ -1065,10 +1112,12 @@ async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> Norganization=team.organization,report_id=input.report_id,signal_count=input.signal_count,- run_count=run_count,+ run_count=transition.run_count,source_products=input.source_products,result="pending_input",pending_reason=input.pending_reason,+ chart_count=transition.chart_count,+ charts_enabled=input.charts_enabled,)logger.debug(f"Marked report {input.report_id} as pending_input",diff --git a/products/signals/backend/test/test_report_telemetry.py b/products/signals/backend/test/test_report_telemetry.pyindex 8500a78a8ada..d34c484474c7 100644--- a/products/signals/backend/test/test_report_telemetry.py+++ b/products/signals/backend/test/test_report_telemetry.py@@ -19,10 +19,20 @@ from products.signals.backend.temporal.summary import (PIPELINE_MODULE_PATH = "products.signals.backend.temporal.summary"+CHART_PAYLOAD = {+ "chart_id": "signups-drop",+ "title": "Daily signups",+ "query": {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery"}},+}+@pytest.mark.asyncio@pytest.mark.django_db-async def test_started_and_ready_fire_expected_captures(ateam):+ "charts_enabled,charts,expected_chart_count",+ [(True, [CHART_PAYLOAD], 1), (False, None, 0)],+)+async def test_started_and_ready_fire_expected_captures(ateam, charts_enabled, charts, expected_chart_count):report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.CANDIDATE,@@ -49,6 +59,8 @@ async def test_started_and_ready_fire_expected_captures(ateam):summary="summary",processed_signal_count=2,source_products=source_products,+ charts=charts,+ charts_enabled=charts_enabled,))@@ -65,6 +77,13 @@ async def test_started_and_ready_fire_expected_captures(ateam):assert "project" in e["groups"]assert events[0]["properties"].get("result") is Noneassert events[1]["properties"]["result"] == "ready"+ # Pipeline chart rate is only measurable if the completion event carries the chart set.+ assert events[0]["properties"].get("chart_count") is None+ assert events[1]["properties"]["chart_count"] == expected_chart_count+ # A zero count from a team the rollout never opened charts to is not the agent declining to+ # chart, so the count only reads as a rate next to the rollout state the run saw.+ assert events[1]["properties"]["charts_enabled"] is charts_enabled+ assert "charts_enabled" not in events[0]["properties"]@pytest.mark.asyncio@@ -95,6 +114,7 @@ async def test_failed_fires_completed_with_failure_reason(ateam):kwargs = pipeline_calls[0].kwargsassert kwargs["event"] == "signal_report_completed"assert kwargs["properties"]["result"] == "failed"+ assert "chart_count" not in kwargs["properties"]assert kwargs["properties"]["failure_reason"] == "safety_judge_rejected"assert kwargs["properties"]["signal_count"] == 3assert kwargs["properties"]["source_products"] == ["zendesk"]@@ -233,6 +253,10 @@ async def test_pending_input_fires_completed_and_status_changed_with_pending_reacalls_by_event = {call.kwargs["event"]: call.kwargs for call in capture.call_args_list}assert calls_by_event["signal_report_completed"]["properties"]["result"] == "pending_input"assert calls_by_event["signal_report_completed"]["properties"]["pending_reason"] == pending_reason+ assert calls_by_event["signal_report_completed"]["properties"]["chart_count"] == 0+ # No research ran to ask about the rollout here, so the property stays absent rather than+ # reporting a team as opted out of charts.+ assert "charts_enabled" not in calls_by_event["signal_report_completed"]["properties"]assert calls_by_event["signal_report_status_changed"]["properties"]["pending_reason"] == pending_reasondiff --git a/products/signals/backend/test/test_research_prompt.py b/products/signals/backend/test/test_research_prompt.pyindex 2fc721c583a7..598a1556cb6f 100644--- a/products/signals/backend/test/test_research_prompt.py+++ b/products/signals/backend/test/test_research_prompt.py@@ -1,9 +1,11 @@+import loggingfrom datetime import datetimeimport pytestfrom products.signals.backend.report_charts import ReportChartfrom products.signals.backend.report_generation.research import (+ ReportPresentationOutput,SignalFinding,_render_previous_metrics_context,_render_signal_for_research,@@ -243,3 +245,61 @@ class TestBuildReportPresentationPrompt:assert '"comparison"' not in promptassert "Previous period" not in prompt+++class TestReportPresentationOutputCharts:+ # Title, summary, and charts arrive as one response, so a chart that fails validation used to+ # take the whole presentation step down and end the research run with no report.+ def test_a_malformed_chart_is_dropped_and_the_rest_of_the_response_survives(self):+ parsed = ReportPresentationOutput.model_validate(+ {+ "title": "fix(signups): Handle the drop",+ "summary": "Signups fell 60% over the week.",+ "charts": [+ {+ "chart_id": "signups-drop",+ "title": "Daily signups",+ "query": {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery"}},+ },+ {"chart_id": "bare-trends", "title": "Wrong node", "query": {"kind": "TrendsQuery"}},+ ],+ }+ )++ assert parsed.title == "fix(signups): Handle the drop"+ assert [chart.chart_id for chart in parsed.charts] == ["signups-drop"]++ def test_the_dropped_chart_warning_names_the_rule_without_the_rejected_query(self, caplog):+ with caplog.at_level(logging.WARNING):+ ReportPresentationOutput.model_validate(+ {+ "title": "fix(signups): Handle the drop",+ "summary": "Signups fell 60% over the week.",+ "charts": [+ {+ "chart_id": "leaky",+ "title": "Wrong node",+ "query": {"kind": "HogQLQuery", "query": "SELECT email FROM persons WHERE team='acme'"},+ }+ ],+ }+ )++ warning = "".join(record.getMessage() for record in caplog.records)+ # Pydantic renders the rejected input in the error's own text, so logging it would copy the+ # chart's query into application logs.+ assert "SELECT email" not in warning+ assert "acme" not in warning+ assert "query: value_error" in warning++ def test_a_response_whose_every_chart_is_malformed_still_yields_the_prose(self):+ parsed = ReportPresentationOutput.model_validate(+ {+ "title": "fix(signups): Handle the drop",+ "summary": "Signups fell 60% over the week.",+ "charts": [{"chart_id": "NOT A SLUG", "title": "Bad id", "query": {"kind": "InsightVizNode"}}],+ }+ )++ assert parsed.charts == []+ assert parsed.summary == "Signups fell 60% over the week."