: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): let scouts merge duplicate reports with attribution (#120397)
posthog[bot]5b4da937d1c6
diff --git a/products/signals/backend/report_merge.py b/products/signals/backend/report_merge.pyindex 74f6f81ba611..597d3b91acef 100644--- a/products/signals/backend/report_merge.py+++ b/products/signals/backend/report_merge.py@@ -39,6 +39,7 @@ from products.signals.backend.models import (SignalReportArtefact,SignalReportCheck,SignalReportGithubComment,+ SignalScoutRun,)from products.signals.backend.recurrence import latest_recurrence_reportfrom products.signals.backend.signal_metadata import REASSIGN_SIGNAL_ROW_CAP@@ -114,6 +115,8 @@ class MergedSource:class MergeResult:survivor_id: strsources: tuple[MergedSource, ...]+ # The skill of the scout run that asked for the merge, None for every other caller.+ scout_skill_name: str | None = Nonedef was_merged_away(report: SignalReport) -> bool:@@ -339,6 +342,24 @@ def _survivor_note(sources: list[SignalReport], reason: str | None) -> str:return f"{body}\n\nTitles and summaries are not combined by a merge."+def _acting_scout_skill_name(team_id: int, attribution: ArtefactAttribution) -> str | None:+ """The scout whose run asked for the merge, so its merges can be told apart from other tasks'.++ A task attribution reads the same for a scout, a research run and an implementation run. A task+ can hold several runs (a retried dispatch), and they all share the skill.+ """+ if attribution.task_id is None:+ return None+ skill_name = (+ SignalScoutRun.objects.for_team(team_id)+ .filter(task_run__task_id=attribution.task_id)+ .order_by("-created_at")+ .values_list("skill_name", flat=True)+ .first()+ )+ return skill_name or None++def _requested_source_ids(source_ids: list[str], *, survivor_id: str) -> list[str]:"""The sources to merge, de-duplicated and in request order, or a `ReportMergeError`."""if not source_ids:@@ -390,6 +411,7 @@ def merge_reports(reason about a half-merged pair."""ordered_ids = _requested_source_ids(source_ids, survivor_id=str(survivor.id))+ scout_skill_name = _acting_scout_skill_name(team.id, attribution)with transaction.atomic():# Locked in id order, survivor included, so overlapping merges queue instead of deadlocking.@@ -423,7 +445,7 @@ def merge_reports(SignalReportArtefact.add_log(team_id=team.id,report_id=str(survivor.id),- content=NoteArtefact(note=_survivor_note(sources, reason)),+ content=NoteArtefact(note=_survivor_note(sources, reason), author=scout_skill_name),attribution=attribution,)@@ -440,8 +462,9 @@ def merge_reports(team_id=team.id,survivor_report_id=str(survivor.id),source_report_ids=[item.report_id for item in merged],+ scout_skill_name=scout_skill_name,)- return MergeResult(survivor_id=str(survivor.id), sources=tuple(merged))+ return MergeResult(survivor_id=str(survivor.id), sources=tuple(merged), scout_skill_name=scout_skill_name)def _schedule_signal_move(*, team_id: int, survivor_id: str, source_ids: list[str]) -> None:diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex 827066965d62..96a1929ca0d8 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -204,6 +204,7 @@ _REPORT_CLOSE_OUT_STEP = _CLOSE_OUT_STEP_TEMPLATE.format(number=6, output="repor_REPORT_STEPS_BOTH = """4. **Search the inbox before you author.** A report you'd write may already exist. ALWAYS check first (see *Authoring vs. editing: search the inbox first*) and edit the existing one rather than minting a near-duplicate.5. **Author or edit.** For each issue worth surfacing, decide whether to:- **Edit** an existing report (`scout-edit-report`) when one already covers it. This is the default when a match exists.+ - **Merge** live reports that cover the same issue (`inbox-reports-merge`, see **Merge live duplicates** under *Authoring vs. editing: search the inbox first*), then rewrite the survivor.- **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.@@ -221,6 +222,7 @@ _REPORT_STEPS_EMIT_ONLY = """4. **Search the inbox before you author.** A report_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.+ - **Merge** live reports that cover the same issue (`inbox-reports-merge`, see **Merge live duplicates** under *Editing existing reports*), then rewrite the survivor.- **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.@@ -476,12 +478,17 @@ _EDIT_EVIDENCE_VS_NOTE = (_EDIT_REPOSITORY_BULLET = "- **Fix a misrouted report.** If a report points at the wrong codebase, set `repository` to the right `owner/repo` instead of authoring a duplicate that carries the correct one. It replaces the report's target and re-runs autostart, so a report that had no repository to open a PR against can now open a draft PR. Pass `NO_REPO` when nothing under version control could change, and omit the field entirely when the target is already right. The response carries `repository`, the target the report holds afterwards — read it back to confirm the correction landed."+# Rendered only for personas that hold `edit_report`, because the merge leaves the survivor's title+# and summary as they were and the scout has to rewrite them afterwards.+_MERGE_DUPLICATES_BULLET = "- **Merge live duplicates.** When two or more *live* reports describe the same issue (one root cause, one fix), fold them into one with `inbox-reports-merge` instead of editing each. Call it on the survivor, which should be the older report or the one with an open implementation pull request, and give a one-line `reason`. Reports that are only related are not duplicates: leave both, and name the other report in an `append_note`. Don't merge when a person holds a claim on either report or a source has an open pull request. Append a note on the survivor that names the twin, and let the person decide. A merge doesn't combine titles or summaries, so afterwards `inbox-reports-retrieve` the survivor, rewrite its `title` / `summary` to cover both with `scout-edit-report`, and repoint every `report:` scratchpad entry that named a merged report at the survivor."+_AUTHORING_VS_EDITING_REPORT_BOTH = f"""# Authoring vs. editing: search the inbox first`scout-emit-report` has no dedupe matcher: two calls covering one issue in different words author two reports. Duplicate reports are the main failure mode here, so the discipline is **search, then decide**:{_REPORT_SEARCH_BULLET}- **Edit when it already exists *and is still live*.** If a report covers the issue, prefer `scout-edit-report`. {_EDIT_EVIDENCE_VS_NOTE} Rewrite `title`/`summary` only on a report you own. One living report beats three near-duplicates fragmenting the inbox. But `edit_report` can't change a report's status, so appending to a `resolved` / `suppressed` / `failed` report buries a real relapse under a closed item: when the match is no longer live, treat the relapse as genuinely new, author a fresh report, and repoint your `report:` pointer at it.+{_MERGE_DUPLICATES_BULLET}{_EDIT_REPOSITORY_BULLET}- **Author only when it's genuinely new.** A materially new issue, a known one with new evidence that changes the verdict, or a relapse whose prior report is no longer live. {_REPORT_RETRY_RULE_BOTH}"""@@ -500,6 +507,7 @@ This run updates reports that already exist; it can't author new ones. Find the- **Find it.** {_INBOX_SEARCH_RECIPE} Status matters twice over here: appending to a dismissed or closed report buries your evidence under an item nobody is watching. Reuse the `report:<domain>:<entity>` scratchpad entry from a prior run when you have one. {_DISMISSAL_CONTEXT}- **Append, or rewrite.** Prefer appending. {_EDIT_EVIDENCE_VS_NOTE} Rewrite `title`/`summary` only on a report you own, and only when the framing is genuinely stale; lead the summary with the verdict (see *Writing the summary*).- **Route an unrouted report.** If a report surfaced assigned to no one, set `suggested_reviewers` to route it to an owner: each reviewer an object, `{{user_uuid}}` (preferred — it names a PostHog member directly, with or without a GitHub account) or `{{github_login}}` (a bare lowercase login, no `@`), never a bare string. If the owner isn't named in the report, call `scout-members-list` for this project's members (the org-scoped `org-member-get-github-login` / `org-members-list` tools aren't available in a scout run). This replaces the report's reviewer list and re-runs autostart, so a report that already has a repo and priority but lacked a qualifying reviewer can now open a draft PR. Only set a reviewer you're confident owns the area; an empty list is a no-op.+{_MERGE_DUPLICATES_BULLET}{_EDIT_REPOSITORY_BULLET}- **Don't retry blindly.** `edit_report` is NOT idempotent. A retried `append_note` adds a second note. A retried `append_evidence` adds duplicate signals and increases the report counters again. If unsure whether an edit landed, re-read the report rather than re-sending."""diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 39d24e5a52b1..84e053a68c4a 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -1267,6 +1267,10 @@ class TestPromptBuilder(BaseTest):assert "include_unlisted=true" in promptassert "dismissal_note" in promptassert "record the rationale in your own words" in prompt+ # A scout that finds two live twins must fold them together and then rewrite the survivor,+ # because a merge leaves the survivor's title and summary as they were.+ assert "inbox-reports-merge" in prompt+ assert "rewrite its `title` / `summary` to cover both" in prompt# Report authors need the metric semantics the generated tool shape cannot express on its own:# distinct people, a live bounded query, and whole-window rather than summed-bucket totals.assert "Measuring report impact" in prompt@@ -1509,6 +1513,8 @@ class TestPromptBuilder(BaseTest):assert "include_all_statuses=true" in promptassert "dismissal_note" in promptassert "record the rationale in your own words" in prompt+ # The edit-only section is a separate constant, so it can lose the merge guidance on its own.+ assert "inbox-reports-merge" in prompt@parameterized.expand([diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 0ef2b66cbaa7..823ff8f01af0 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -3903,6 +3903,49 @@ class TestSignalReportMergeAPI(APIBaseTest):source.refresh_from_db()assert source.status == SignalReport.Status.SUPPRESSED+ @parameterized.expand(+ [+ ("person", None, None),+ ("scout_task", "signals-scout-error-tracking", "signals-scout-error-tracking"),+ ("non_scout_task", "", None),+ ]+ )+ def test_merge_attributes_a_scout_merge_to_its_skill(self, _name, scout_skill, expected_author):+ survivor = self._report()+ source = self._report()+ headers: dict[str, str] = {}+ task_id: str | None = None+ if scout_skill is not None:+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ task = Task.objects.create(team=self.team, title="task", description="desc")+ task_id = str(task.id)+ headers["X-PostHog-Task-Id"] = task_id+ if scout_skill:+ SignalScoutRun.objects.create(+ team=self.team,+ task_run=TaskRun.objects.create(task=task, team=self.team),+ skill_name=scout_skill,+ skill_version=1,+ )++ with (+ patch("products.signals.backend.views.report_user_action") as report_action,+ self.captureOnCommitCallbacks(execute=False),+ ):+ response = self.client.post(+ self._merge_url(str(survivor.id)),+ data=json.dumps({"source_report_ids": [str(source.id)]}),+ content_type="application/json",+ headers=headers,+ )+ assert response.status_code == status.HTTP_200_OK, response.json()++ note = SignalReportArtefact.objects.get(report_id=survivor.id, type="note")+ assert NoteArtefact.model_validate_json(note.content).author == expected_author+ properties = report_action.call_args.kwargs["properties"]+ assert (properties["task_id"], properties["scout_skill_name"]) == (task_id, expected_author)+def test_merge_schedules_the_signal_move_once_committed(self):survivor = self._report()source = self._report()diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 86ef83c5cac8..36e0303bec30 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -3075,6 +3075,8 @@ class SignalReportViewSet("organization_id": str(self.organization.id),"report_id": result.survivor_id,"actor_kind": attribution.kind,+ "task_id": attribution.task_id,+ "scout_skill_name": result.scout_skill_name,"source_count": len(result.sources),"released_claim_count": sum(1 for source in result.sources if source.released_claim),"signals_moved": sum(source.signals_moved for source in result.sources),