: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
fix(signals): keep report content when repository selection fails (#109624)
posthog[bot]cb123fa3d8c3
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 8852cebc1cd1..2f00eae5c556 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -510,13 +510,19 @@ class SignalReport(UUIDModel):self.error = Noneupdated_fields.update(["title", "summary", "error"])+ # A `None` title or summary keeps the current one, so a run that did no research (e.g. no+ # repository selected) does not erase the content the report is searched and deduplicated by.case (S.IN_PROGRESS, S.PENDING_INPUT):- if title is None or summary is None or error is None:- raise ValueError("title, summary, and error are required for in_progress -> pending_input")- self.title = title- self.summary = summary+ if error is None:+ raise ValueError("error is required for in_progress -> pending_input")+ if title is not None:+ self.title = title+ updated_fields.add("title")+ if summary is not None:+ self.summary = summary+ updated_fields.add("summary")self.error = error- updated_fields.update(["title", "summary", "error"])+ updated_fields.add("error")# Reset to potential (from in_progress via actionability judge, from suppressed, or by user snooze)case (S.IN_PROGRESS | S.PENDING_INPUT | S.SUPPRESSED | S.READY | S.RESOLVED | S.FAILED, S.POTENTIAL):diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex cbbcc134d018..f86305f2de38 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -29,13 +29,19 @@ from posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.artefact_schemas import NoteArtefactfrom products.signals.backend.auto_start import (RequestedImplementation,maybe_autostart_from_report_artefacts,start_requested_implementation,)from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate-from products.signals.backend.models import SIGNALS_AT_RUN_INCREMENT, SignalReport, SignalTeamConfig+from products.signals.backend.models import (+ SIGNALS_AT_RUN_INCREMENT,+ SignalReport,+ SignalReportArtefact,+ SignalTeamConfig,+)from products.signals.backend.quota import (capture_signal_report_quota_paused,record_quota_check_failed_open,@@ -166,12 +172,20 @@ class ReportDecision:# 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- # prompts about the old report under the new one. Not a constant so the pipeline can author its- # own set later without moving the write.- suggested_prompts: list[str] = field(default_factory=list)+ # Suggested prompts to store with the title/summary. `[]` when the decision carries a freshly+ # written title and summary, because the pipeline does not author prompts yet: whatever a scout+ # suggested was written against the prose this decision replaces, so leaving it would put+ # prompts about the old report under the new one. `None` for the no-repo branch, which keeps+ # the prose and so keeps the prompts too.+ suggested_prompts: list[str] | None = field(default_factory=list)+ # Work-log note to append with the transition. The no-repo branch records its blocker here+ # instead of in the title/summary.+ note: str | None = None+ # Set by the no-repo branch, which does no research. Its `title`/`summary` are placeholders that+ # fill only blank fields (a recurrence of a safety-failed report starts blank), so a report keeps+ # the content it is searched and deduplicated by. They stay non-null because an older activity+ # worker in a rolling deploy rejects `None`.+ keep_existing_content: bool = False# Which of the two doors into PENDING_INPUT produced this decision, so telemetry can tell a# broken repo-selection integration apart from the agent legitimately asking for human input.# Irrelevant (left `None`) unless `choice == ActionabilityChoice.REQUIRES_HUMAN_INPUT`.@@ -432,11 +446,15 @@ class SignalReportSummaryWorkflow:"Report has no repository selected",reason=repo_result.reason,)+ blocker = f"Could not automatically select a repository: {repo_result.reason}"decision = ReportDecision(title="Repository selection required",- summary=f"Could not automatically select a repository: {repo_result.reason}",+ summary=blocker,choice=ActionabilityChoice.REQUIRES_HUMAN_INPUT,explanation=repo_result.reason,+ suggested_prompts=None,+ note=blocker,+ keep_existing_content=True,pending_reason="repo_selection_required",)else:@@ -521,6 +539,8 @@ class SignalReportSummaryWorkflow:suggested_prompts=decision.suggested_prompts,charts_enabled=decision.charts_enabled,pending_reason=decision.pending_reason,+ note=decision.note,+ keep_existing_content=decision.keep_existing_content,),start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=3),@@ -1201,8 +1221,9 @@ async def mark_report_failed_activity(input: MarkReportFailedInput) -> None:class MarkReportPendingInput:team_id: intreport_id: str- title: str- summary: str+ # `None` keeps the report's current title/summary.+ title: str | None+ summary: str | Nonereason: strsignal_count: int = 0source_products: list[str] = field(default_factory=list)@@ -1227,6 +1248,10 @@ class MarkReportPendingInput:# Coarse cause of the transition ("repo_selection_required" / "agent_requested"), see# ReportDecision.pending_reason.pending_reason: str | None = None+ # See ReportDecision.note. Appended to the work log in the same transaction.+ note: str | None = None+ # See ReportDecision.keep_existing_content.+ keep_existing_content: bool = False@temporalio.activity.defn@@ -1241,8 +1266,10 @@ async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> Nreport = SignalReport.objects.select_for_update().get(id=input.report_id, team_id=input.team_id)if report.status == SignalReport.Status.PENDING_INPUT:return _ReportTransition(run_count=report.run_count, chart_count=0, was_duplicate=True)+ title = report.title if input.keep_existing_content and report.title else input.title+ summary = report.summary if input.keep_existing_content and report.summary else input.summaryupdated_fields = report.transition_to(- SignalReport.Status.PENDING_INPUT, title=input.title, summary=input.summary, error=input.reason+ SignalReport.Status.PENDING_INPUT, title=title, summary=summary, error=input.reason)if input.charts is not None:report.charts = input.charts@@ -1258,6 +1285,13 @@ async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> Nreport._pending_reason = input.pending_reason # type: ignore[attr-defined]report.save(update_fields=updated_fields)_write_research_checks(report, input)+ if input.note is not None:+ SignalReportArtefact.add_log(+ team_id=input.team_id,+ report_id=input.report_id,+ content=NoteArtefact(note=input.note),+ attribution=ArtefactAttribution.system(),+ )return _ReportTransition(run_count=report.run_count, chart_count=len(report.charts or []), was_duplicate=False)diff --git a/products/signals/backend/test/test_report_telemetry.py b/products/signals/backend/test/test_report_telemetry.pyindex 6ad6595ab5a4..4b9c8243443c 100644--- a/products/signals/backend/test/test_report_telemetry.py+++ b/products/signals/backend/test/test_report_telemetry.py@@ -3,7 +3,7 @@ from unittest.mock import patchfrom posthog.sync import database_sync_to_async-from products.signals.backend.models import SignalReport, SignalReportCheck+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportCheckfrom products.signals.backend.temporal.summary import (MarkReportFailedInput,MarkReportInProgressInput,@@ -260,6 +260,64 @@ async def test_pending_input_fires_completed_and_status_changed_with_pending_reaassert calls_by_event["signal_report_status_changed"]["properties"]["pending_reason"] == pending_reason+ "stored_title,stored_summary,expected_title,expected_summary",+ [+ (+ "Checkout button does nothing on Safari",+ "Users on Safari click checkout and nothing happens.",+ "Checkout button does nothing on Safari",+ "Users on Safari click checkout and nothing happens.",+ ),+ ("", "", "Repository selection required", "Could not automatically select a repository: no repository matched"),+ ],+ ids=["keeps_stored_content", "fills_blank_content"],+)+async def test_pending_input_without_new_content_keeps_title_summary_and_logs_note(+ ateam, stored_title, stored_summary, expected_title, expected_summary+):+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.IN_PROGRESS,+ signal_count=3,+ total_weight=2.0,+ title=stored_title,+ summary=stored_summary,+ suggested_prompts=["Why does checkout fail on Safari?"],+ )+ report_id = str(report.id)++ with patch(f"{PIPELINE_MODULE_PATH}.posthoganalytics.capture"):+ await mark_report_pending_input_activity(+ MarkReportPendingInput(+ team_id=ateam.id,+ report_id=report_id,+ title="Repository selection required",+ summary="Could not automatically select a repository: no repository matched",+ reason="Requires human input: no repository matched",+ pending_reason="repo_selection_required",+ note="Could not automatically select a repository: no repository matched",+ keep_existing_content=True,+ )+ )++ refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report_id)+ assert refreshed.status == SignalReport.Status.PENDING_INPUT+ assert refreshed.title == expected_title+ assert refreshed.summary == expected_summary+ assert refreshed.suggested_prompts == ["Why does checkout fail on Safari?"]+ assert refreshed.error == "Requires human input: no repository matched"+ notes = await database_sync_to_async(+ lambda: list(+ SignalReportArtefact.objects.filter(report_id=report_id, type=SignalReportArtefact.ArtefactType.NOTE)+ )+ )()+ assert len(notes) == 1+ assert "no repository matched" in notes[0].content++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_pending_input_is_idempotent_when_already_pending_input(ateam):diff --git a/products/signals/backend/test/test_summary_workflow.py b/products/signals/backend/test/test_summary_workflow.pyindex 56af13c5f508..b77fa40eb8da 100644--- a/products/signals/backend/test/test_summary_workflow.py+++ b/products/signals/backend/test/test_summary_workflow.py@@ -182,6 +182,7 @@ class _Recorder:research_choice: ActionabilityChoice = ActionabilityChoice.NOT_ACTIONABLE,research_metrics: list[dict[str, object]] | None = None,checks_snapshot: dict[str, str] | None = None,+ selected_repository: str | None = "owner/repo",) -> None:self.gate_answers = gate_answers or {}self.fetch_results = fetch_results or [[_signal_data()]]@@ -190,6 +191,7 @@ class _Recorder:self.research_metrics = research_metricsself.checks_snapshot = checks_snapshotself.checks_summary: str | None = None+ self.selected_repository = selected_repositoryself.gate_checks: list[str] = []self.fetches = 0self.assigned_signal_checks = 0@@ -265,7 +267,7 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:@activity.defn(name="select_repository_activity")async def fake_select_repo(input: SelectRepositoryInput) -> RepoSelectionResult:recorder.repo_selections += 1- return RepoSelectionResult(repository="owner/repo", reason="selected")+ return RepoSelectionResult(repository=recorder.selected_repository, reason="no repository matched")@activity.defn(name="run_agentic_report_activity")async def fake_research(input: RunAgenticReportInput) -> RunAgenticReportOutput:@@ -403,6 +405,23 @@ async def test_metric_payload_reaches_the_report_transition(choice, target):assert inputs[0].checks_summary == recorder.checks_summary+async def test_no_repository_keeps_report_content_and_logs_the_blocker():+ recorder = _Recorder(selected_repository=None)++ await _run_summary_workflow(recorder)++ assert recorder.researches == 0+ assert len(recorder.pending_inputs) == 1+ pending = recorder.pending_inputs[0]+ assert pending.keep_existing_content is True+ assert pending.title == "Repository selection required"+ assert pending.summary == "Could not automatically select a repository: no repository matched"+ assert pending.suggested_prompts is None+ assert pending.pending_reason == "repo_selection_required"+ assert pending.note == "Could not automatically select a repository: no repository matched"++# ---------------------------------------------------------------------------# Empty fetch: ClickHouse lag must not fail a report that has signals assigned# ---------------------------------------------------------------------------