: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): merge duplicate inbox reports into one surviving report (#104346)
posthog[bot]b6cbe480f70a
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 5bcc7349e847..c3cb0392c229 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -973,6 +973,7 @@ Read + delete + state transitions. Uses `IsAuthenticated` + `APIScopePermission`| GET | `signals/reports/{id}/` | Retrieve a single report || DELETE | `signals/reports/{id}/` | Soft-delete a report and its signals. Starts `SignalReportDeletionWorkflow`. On success returns `202`. If the workflow is already running, returns `200 {"status": "already_running"}`. The API immediately transitions the Postgres report to `deleted` to hide it from list results while ClickHouse cleanup runs asynchronously. || POST | `signals/reports/{id}/state/` | Transition report state. Body: `{ "state": "suppressed" \| "potential" \| "resolved", ...transition_to kwargs }`. `suppressed`, `potential`, and `resolved` are exposed via API (`resolved` for user-driven "work is done"; the model still gates which statuses may resolve). Returns `409` on invalid transitions and `400` on invalid arguments. |+| POST | `signals/reports/{id}/merge/` | Merge duplicate reports into this one. Body: `{ "source_report_ids": [...], "reason": "..." }`. One transaction moves the sources' signals, log artefacts, pull requests, task runs and checks onto the survivor, then archives each source with reason `merged` and a `duplicate_of` link back. See `report_merge.py`. || POST | `signals/reports/{id}/reingest/` | Delete a report and re-ingest its signals. Starts `SignalReportReingestionWorkflow`. On success returns `202`. If already running, returns `200 {"status": "already_running"}`. Same team access as other report endpoints; personal API keys need `task:write`. || GET | `signals/reports/{id}/artefacts/` | List **all** artefacts for a report, ordered by `-created_at` || GET | `signals/reports/{id}/signals/` | Fetch all signals for a report from ClickHouse, including full metadata |diff --git a/products/signals/backend/report_merge.py b/products/signals/backend/report_merge.pynew file mode 100644index 000000000000..38bb9f502fd7--- /dev/null+++ b/products/signals/backend/report_merge.py@@ -0,0 +1,464 @@+"""Fold duplicate reports into the one report that survives them.++Grouping puts the same issue in two reports often enough that the inbox needs a repair tool, and+the pieces of that repair cannot be composed safely by hand. Signals live in ClickHouse and have+to be re-emitted under the survivor's id, the duplicate's dismissal must not close a pull request+the survivor now owns, and the two reports' counters have to stay consistent. So the whole thing+is one operation with one transaction.++The caller names the survivor and the sources. Nothing here guesses which report should win, and+nothing here rewrites content: titles, summaries, charts and metrics are left exactly as they+were, so the survivor's embeddings are untouched and the outcome of a merge is predictable+without reading an LLM's mind. A caller that wants a combined summary edits the survivor+afterwards, where the safety judge runs.+"""++from __future__ import annotations++from uuid import UUID++from django.db import transaction+from django.db.models import F+from django.db.models.functions import Coalesce++import structlog++from posthog.dataclasses import frozen+from posthog.models.team import Team++from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.artefact_schemas import (+ ArtefactContentValidationError,+ Dismissal,+ NoteArtefact,+ ReportLink,+)+from products.signals.backend.enums import ReportLinkKind+from products.signals.backend.models import (+ SignalReport,+ SignalReportArtefact,+ SignalReportCheck,+ SignalReportGithubComment,+)+from products.signals.backend.recurrence import latest_recurrence_report+from products.signals.backend.signal_metadata import REASSIGN_SIGNAL_ROW_CAP++logger = structlog.get_logger(__name__)++# One call folds a handful of twins at most. The cap bounds the row locks the merge takes and the+# ClickHouse re-emits it schedules.+MAX_MERGE_SOURCE_REPORTS = 10+MAX_MERGE_REASON_LENGTH = 500++# Deliberately not in `SIGNAL_REPORT_DISMISSAL_REASON_CHOICES`. Like `refunded`, this server path+# writes it and no caller may pick it, because `merge_survivor` reads it to decide whether a+# `duplicate_of` link redirects signals.+MERGE_DISMISSAL_REASON = "merged"++# Both ends of a merge must be a live report. A resolved or already-archived source has had its+# verdict, and folding it in would undo that verdict silently. A resolved survivor is terminal for+# new signals, so it would take the sources' signals somewhere the pipeline never looks at again+# while archiving those sources for good.+#+# IN_PROGRESS is excluded although it is live: a research run is writing to that report right now,+# and `SUPPRESSED -> READY` is a legal transition, so `mark_report_ready_activity` would resurrect+# the report after the merge moved its signals and work log away. CANDIDATE is safe because a run+# that starts later needs `SUPPRESSED -> IN_PROGRESS`, which the model refuses.+MERGEABLE_STATUSES = frozenset(+ {+ SignalReport.Status.POTENTIAL,+ SignalReport.Status.CANDIDATE,+ SignalReport.Status.PENDING_INPUT,+ SignalReport.Status.READY,+ SignalReport.Status.FAILED,+ }+)++# Log artefacts describe work done on a report, so they follow the work to the survivor. Three+# families stay behind, each because moving them corrupts the survivor:+# - `report_link` / `related_to` state how *the source* relates to other reports, so a moved row+# can make the survivor link to itself or close a cycle `validate_report_link` would refuse.+# - `title_change` / `summary_change` would claim the survivor's title changed to the source's.+# - `work_claim` / `work_release` decide ownership, and `active_claims` reads the newest claim per+# report, so a moved claim can mask the survivor's live claim.+# `signal_finding` is in neither family and is the per-signal evidence, so it moves with them.+_MOVED_ARTEFACT_TYPES = frozenset(SignalReportArtefact.LOG_ARTEFACT_TYPES) - {+ SignalReportArtefact.ArtefactType.REPORT_LINK,+ SignalReportArtefact.ArtefactType.RELATED_TO,+ SignalReportArtefact.ArtefactType.TITLE_CHANGE,+ SignalReportArtefact.ArtefactType.SUMMARY_CHANGE,+ SignalReportArtefact.ArtefactType.WORK_CLAIM,+ SignalReportArtefact.ArtefactType.WORK_RELEASE,+} | {SignalReportArtefact.ArtefactType.SIGNAL_FINDING}+++class ReportMergeError(Exception):+ """A merge the caller asked for cannot be applied. `detail` is caller-facing."""++ def __init__(self, detail: str) -> None:+ super().__init__(detail)+ self.detail = detail+++@frozen+class MergedSource:+ """What the merge did to one source report."""++ report_id: str+ artefacts_moved: int+ signals_moved: int+ released_claim: bool+++@frozen+class MergeResult:+ survivor_id: str+ sources: tuple[MergedSource, ...]+++def was_merged_away(report: SignalReport) -> bool:+ """Whether this report was folded into another one and so no longer holds its own signals.++ Any `merged` dismissal counts, unlike `fixed_dismissal_at`, which reads only the latest. A+ fixed dismissal is a verdict a reviewer can overrule; a merge is structural. The signals and+ the work log are on the survivor either way, so a later dismissal with another code must not+ make the report restorable or stop it redirecting matches.+ """+ if report.status != SignalReport.Status.SUPPRESSED:+ return False+ for content in SignalReportArtefact.objects.filter(+ team_id=report.team_id,+ report_id=report.id,+ type=SignalReportArtefact.ArtefactType.DISMISSAL,+ ).values_list("content", flat=True):+ try:+ if Dismissal.model_validate_json(content).reason == MERGE_DISMISSAL_REASON:+ return True+ except ValueError:+ continue+ return False+++def _merge_target(report: SignalReport, *, lock: bool) -> SignalReport | None:+ """The report this one was merged into, or None when it was not merged away."""+ if not was_merged_away(report):+ return None+ for content in (+ SignalReportArtefact.objects.filter(+ team_id=report.team_id,+ report_id=report.id,+ type=SignalReportArtefact.ArtefactType.REPORT_LINK,+ )+ .order_by("-created_at")+ .values_list("content", flat=True)+ ):+ try:+ link = ReportLink.model_validate_json(content)+ except ValueError:+ continue+ if link.kind != ReportLinkKind.DUPLICATE_OF:+ continue+ survivors = SignalReport.objects.filter(team_id=report.team_id, id=link.report_id).exclude(+ status=SignalReport.Status.DELETED+ )+ if lock:+ survivors = survivors.select_for_update()+ return survivors.first()+ return None+++def merge_survivor(report: SignalReport, *, lock: bool = False) -> SignalReport:+ """Follow the merge chain to the report that now holds this one's signals.++ Grouping calls this before attaching a signal. A merged report keeps absorbing matches+ otherwise: its signals stay in the semantic index under its own id until the re-emit lands,+ and a suppressed report accrues them silently, so the duplicate the merge just archived would+ quietly grow again.+ """+ visited = {report.id}+ while survivor := _merge_target(report, lock=lock):+ if survivor.id in visited:+ return report+ visited.add(survivor.id)+ report = survivor+ return report+++def signal_target_report(report: SignalReport, *, lock: bool = False) -> SignalReport:+ """The report a signal that matched `report` should actually attach to.++ Two pointers can move a match: a merge sends it to the survivor, and a recurrence sends it to+ the fresh report a resolved one spawned. Either can follow the other (a survivor is later+ resolved and recurs, a recurrence is later merged away), so this walks both until the report+ stops moving.+ """+ visited: set[UUID] = set()+ while report.id not in visited:+ visited.add(report.id)+ resolved = merge_survivor(latest_recurrence_report(report, lock=lock), lock=lock)+ if resolved.id == report.id:+ break+ report = resolved+ return report+++def _release_source_claim(source: SignalReport, attribution: ArtefactAttribution) -> bool:+ """End any active claim on the source, so no claim is left stranded on an archived report.++ Claim history stays on the source (see `_MOVED_ARTEFACT_TYPES`), so a claim left active there+ would make the survivor look unclaimed while the work is still owned, and another actor could+ take it. That holds whoever owns the claim, the merge caller included: they re-claim the+ survivor, which is the report the work now belongs to.+ """+ from products.signals.backend.report_assignments import (+ release_claim, # noqa: PLC0415 — keeps the GitHub integration off the grouping import path+ )+ from products.signals.backend.report_claims import get_active_claim # noqa: PLC0415 — same++ claim = get_active_claim(team_id=source.team_id, report_id=str(source.id))+ if claim is None:+ return False+ release_claim(claim, attribution)+ return True+++def _move_side_rows(source: SignalReport, survivor: SignalReport) -> None:+ """Re-parent the per-report rows that live outside the artefact log.++ Each of these has a uniqueness constraint the survivor may already satisfy, so a colliding row+ stays on the source rather than failing the merge. Reading either report then still finds the+ fact once.++ `SignalReportTask` stays on the source even though it names the same work. Billing charges one+ flat credit per report whose implementation bridge shipped a pull request in the period+ (`billing.get_signals_billing_credits_by_team`), so moving a bridge would collapse two charges+ into one and could make the survivor look billed in an earlier period. The survivor still+ reaches the work through the `task_run` and `pull_request` artefacts that do move, which is+ what implementation-PR resolution reads.+ """+ survivor_comments = set(+ SignalReportGithubComment.all_teams.filter(report_id=survivor.id).values_list("repository", "number"),+ )+ for comment in SignalReportGithubComment.all_teams.filter(team_id=source.team_id, report_id=source.id):+ if (comment.repository, comment.number) in survivor_comments:+ continue+ comment.report_id = survivor.id+ comment.save(update_fields=["report", "updated_at"])++ SignalReportCheck.objects.for_team(source.team_id).filter(report_id=source.id).update(report_id=survivor.id)+++def _merge_source_into(+ *,+ survivor: SignalReport,+ source: SignalReport,+ attribution: ArtefactAttribution,+ reason: str | None,+) -> MergedSource:+ released_claim = _release_source_claim(source, attribution)++ moved_artefacts = (+ SignalReportArtefact.objects.filter(+ team_id=source.team_id, report_id=source.id, type__in=sorted(_MOVED_ARTEFACT_TYPES)+ )+ # An artefact's `claim` must name a claim on the same report and claim history stays on the+ # source, so the pointer is dropped rather than left dangling. Actor attribution, which is+ # what the work log renders, is preserved.+ .update(report_id=survivor.id, claim=None)+ )++ _move_side_rows(source, survivor)++ # From the source's Postgres counters rather than a ClickHouse count, because the pipeline+ # maintains these and the promotion gate reads them, so the survivor stays exact whatever the+ # re-emit's lag turns out to be. The source keeps its own as a historical record.+ SignalReport.objects.filter(id=survivor.id).update(+ signal_count=F("signal_count") + source.signal_count,+ total_weight=F("total_weight") + source.total_weight,+ # A scout's corroborations past the per-report note cap exist only as this counter, with no+ # artefact rows behind them, so leaving it on the source would drop the only record.+ corroboration_count=Coalesce(F("corroboration_count"), 0) + (source.corroboration_count or 0),+ )++ SignalReportArtefact.add_log(+ team_id=source.team_id,+ report_id=str(source.id),+ content=ReportLink(kind=ReportLinkKind.DUPLICATE_OF, report_id=str(survivor.id), reason=reason),+ attribution=attribution,+ )++ _dismiss_as_merged(source, survivor=survivor, attribution=attribution, reason=reason)++ return MergedSource(+ report_id=str(source.id),+ artefacts_moved=moved_artefacts,+ signals_moved=source.signal_count,+ released_claim=released_claim,+ )+++def _dismiss_as_merged(+ source: SignalReport,+ *,+ survivor: SignalReport,+ attribution: ArtefactAttribution,+ reason: str | None,+) -> None:+ """Archive the source the way every other dismissal surface does: `transition_to` then `save`.++ The `post_save` receivers hang off that save, so the merge gets the tracker-issue close, the+ `signal_report_status_changed` analytics and the embedding tombstone without opting into any+ of them. The pull-request close fires too, and skips itself, because the source's+ `pull_request` artefacts already moved to the survivor inside this transaction and+ `implementation_pr_needed_by_another_report` sees the survivor still holding the PR.+ """+ updated_fields = source.transition_to(SignalReport.Status.SUPPRESSED)+ source._wrote_dismissal_feedback = True # type: ignore[attr-defined]+ source._transition_actor_user_id = attribution.user_id # type: ignore[attr-defined]+ source.save(update_fields=updated_fields)++ note = f"Merged into report {survivor.id}."+ SignalReportArtefact.append_dismissal(+ team_id=source.team_id,+ report_id=str(source.id),+ content=Dismissal(+ reason=MERGE_DISMISSAL_REASON,+ note=f"{note} {reason}" if reason else note,+ user_id=attribution.user_id,+ ),+ attribution=attribution,+ )+++def _survivor_note(sources: list[SignalReport], reason: str | None) -> str:+ listed = "\n".join(f"- {source.id}: {source.title or 'Untitled report'}" for source in sources)+ body = f"Merged {len(sources)} duplicate report{'' if len(sources) == 1 else 's'} into this one:\n{listed}"+ if reason:+ body = f"{body}\n\n{reason}"+ return f"{body}\n\nTitles and summaries are not combined by a merge."+++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:+ raise ReportMergeError("At least one source report is required.")+ if len(source_ids) > MAX_MERGE_SOURCE_REPORTS:+ raise ReportMergeError(+ f"A merge takes at most {MAX_MERGE_SOURCE_REPORTS} source reports. Split it into several calls."+ )+ ordered: list[str] = []+ for raw_id in source_ids:+ key = str(raw_id)+ if key == survivor_id:+ raise ReportMergeError("A report cannot be merged into itself.")+ if key not in ordered:+ ordered.append(key)+ return ordered+++def _mergeable_source(report: SignalReport | None, requested_id: str) -> SignalReport:+ if report is None:+ raise ReportMergeError(f"Report {requested_id} was not found in this project.")+ if report.status not in MERGEABLE_STATUSES:+ raise ReportMergeError(+ f"Report {requested_id} is {report.status} and cannot be merged. Only a live report can be a source."+ )+ # The signal move reads one bounded page and never pages or retries, so a source past the cap+ # would leave the remainder pointing at itself while the survivor's counters already include+ # them. Refusing upfront keeps that inconsistency from being created at all.+ if report.signal_count > REASSIGN_SIGNAL_ROW_CAP:+ raise ReportMergeError(+ f"Report {requested_id} has more than {REASSIGN_SIGNAL_ROW_CAP} signals and is too large to merge."+ )+ return report+++def merge_reports(+ *,+ team: Team,+ survivor: SignalReport,+ source_ids: list[str],+ attribution: ArtefactAttribution,+ reason: str | None = None,+) -> MergeResult:+ """Fold every source report into `survivor`, atomically.++ Raises `ReportMergeError` when the survivor or a source is not a live report of this team, or+ when a source names the survivor itself. Either the whole call applies or none of it does, so a caller never has to+ reason about a half-merged pair.+ """+ ordered_ids = _requested_source_ids(source_ids, survivor_id=str(survivor.id))++ with transaction.atomic():+ # Locked in id order, survivor included, so overlapping merges queue instead of deadlocking.+ locked = {+ str(report.id): report+ for report in SignalReport.objects.select_for_update()+ .filter(team_id=team.id, id__in=sorted({*ordered_ids, str(survivor.id)}))+ .order_by("id")+ }+ if str(survivor.id) not in locked:+ raise ReportMergeError("The report to merge into was not found in this project.")+ survivor = locked[str(survivor.id)]+ if survivor.status not in MERGEABLE_STATUSES:+ raise ReportMergeError(+ f"The report to merge into is {survivor.status} and cannot take on duplicates. "+ "Only a live report can be the survivor."+ )+ sources = [_mergeable_source(locked.get(source_id), source_id) for source_id in ordered_ids]++ try:+ merged = [+ _merge_source_into(survivor=survivor, source=source, attribution=attribution, reason=reason)+ for source in sources+ ]+ except ArtefactContentValidationError as e:+ # `add_log` enforces the `report_link` invariants, so a merge that would close a+ # duplicate_of cycle is a merge the caller cannot have, not a server fault.+ raise ReportMergeError(str(e))++ SignalReportArtefact.add_log(+ team_id=team.id,+ report_id=str(survivor.id),+ content=NoteArtefact(note=_survivor_note(sources, reason)),+ attribution=attribution,+ )++ team_id = team.id+ survivor_id = str(survivor.id)+ moved_ids = [item.report_id for item in merged]+ transaction.on_commit(+ lambda: _schedule_signal_move(team_id=team_id, survivor_id=survivor_id, source_ids=moved_ids)+ )++ survivor.refresh_from_db()+ logger.info(+ "signals_reports_merged",+ team_id=team.id,+ survivor_report_id=str(survivor.id),+ source_report_ids=[item.report_id for item in merged],+ )+ return MergeResult(survivor_id=str(survivor.id), sources=tuple(merged))+++def _schedule_signal_move(*, team_id: int, survivor_id: str, source_ids: list[str]) -> None:+ """Queue the ClickHouse move, and never fail the request if the broker refuses it.++ This runs after the merge has committed, and a retried call answers 409 because the sources+ are archived by then, so raising here would report a completed merge as a 500 with no way to+ re-drive it. Grouping still routes new matches through the merge pointer, so the cost of a+ lost dispatch is that the moved signals stay indexed under the archived source.+ """+ from products.signals.backend.tasks import ( # noqa: PLC0415 — keeps the celery app off the API import path+ move_merged_report_signals,+ )++ try:+ move_merged_report_signals.delay(team_id=team_id, survivor_report_id=survivor_id, source_report_ids=source_ids)+ except Exception:+ logger.exception(+ "signals_merged_report_signal_move_not_queued",+ team_id=team_id,+ survivor_report_id=survivor_id,+ source_report_ids=source_ids,+ )diff --git a/products/signals/backend/signal_metadata.py b/products/signals/backend/signal_metadata.pyindex 8bf54fefe293..ff1bb78fd8b0 100644--- a/products/signals/backend/signal_metadata.py+++ b/products/signals/backend/signal_metadata.py@@ -22,6 +22,12 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.models import Team+# Cap on the signal rows one merge re-points from a source onto its survivor. The move neither+# pages nor retries, so `report_merge` refuses a source above the cap rather than leaving the+# remainder pointing at an archived report while the survivor's counters already include them.+REASSIGN_SIGNAL_ROW_CAP = 5000++# The embedding model whose document rows constitute the signal store; every signals# ClickHouse query filters on it.EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_SMALL_1536diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex eab3c77a5055..6084a808a892 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -612,6 +612,74 @@ def open_implementation_pr_for_review(team_id: int, report_id: str, pr_url: str)open_pull_request_ready_for_review(team_id=team_id, report_id=report_id, pr_url=pr_url)+@shared_task(+ name="products.signals.backend.tasks.move_merged_report_signals",+ ignore_result=True,+ max_retries=0,+)+@with_team_scope()+def move_merged_report_signals(team_id: int, survivor_report_id: str, source_report_ids: list[str]) -> None:+ """Re-emit every merged-away report's ClickHouse signals under the surviving report's id.++ Runs on a worker because the merge's own transaction must not wait on a ClickHouse read plus+ one embedding emission per signal. The Postgres half of the merge is already committed and the+ survivor's counters were taken from the source rows, so the report is consistent while this is+ in flight; what the move buys is semantic search and future grouping pointing at the survivor.+ Best-effort, so this never retries: grouping follows the merge pointer in the meantime+ (`report_merge.merge_survivor`), which is what keeps a signal from re-attaching to the+ duplicate before the rows land.+ """+ from products.signals.backend.report_merge import ( # noqa: PLC0415 — keeps the merge module off the celery import path+ merge_survivor,+ )+ from products.signals.backend.temporal.signal_queries import ( # noqa: PLC0415 — keeps the temporal and hogql deps off the import path+ reassign_report_signals,+ )++ team = Team.objects.get(pk=team_id)+ # Two merges in quick succession (A into B, then B into C) queue two tasks that can run out of+ # order, so the survivor recorded at merge time may itself be merged away by now. Follow the+ # chain here instead, or A's signals land under the archived B and never reach C.+ survivor = SignalReport.objects.filter(team_id=team_id, id=survivor_report_id).first()+ if survivor is None:+ logger.warning(+ "signals_merged_report_signals_survivor_missing",+ team_id=team_id,+ survivor_report_id=survivor_report_id,+ )+ return+ survivor_report_id = str(merge_survivor(survivor).id)++ for source_report_id in source_report_ids:+ try:+ moved = reassign_report_signals(+ source_report_id=source_report_id,+ survivor_report_id=survivor_report_id,+ team_id=team_id,+ team=team,+ )+ except SoftTimeLimitExceeded:+ # Celery's own termination signal. Swallowing it would defeat the soft time limit.+ raise+ except Exception:+ # Each source is an independent ClickHouse read plus its own emissions, and the task+ # does not retry, so one source's failure must not strand the sources after it.+ logger.exception(+ "signals_merged_report_signals_move_failed",+ team_id=team_id,+ survivor_report_id=survivor_report_id,+ source_report_id=source_report_id,+ )+ continue+ logger.info(+ "signals_merged_report_signals_moved",+ team_id=team_id,+ survivor_report_id=survivor_report_id,+ source_report_id=source_report_id,+ signal_count=moved,+ )++def _capture_refund_sync_event(refund: SignalReportRefund, event: str, extra: dict[str, object]) -> None:organization = refund.team.organizationwith ph_scoped_capture() as capture:diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex 6dbe5bde6a28..5e9f1100d31a 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -38,7 +38,8 @@ from products.signals.backend.enums import ReportLinkKindfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gatefrom products.signals.backend.receivers import _is_safety_suppressed-from products.signals.backend.recurrence import fixed_dismissal_at, latest_recurrence_report+from products.signals.backend.recurrence import fixed_dismissal_at+from products.signals.backend.report_merge import signal_target_reportfrom products.signals.backend.signal_metadata import EMBEDDING_MODELfrom products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.drop_telemetry import capture_signal_dropped@@ -509,7 +510,7 @@ async def match_signal_to_report_activity(input: MatchSignalToReportInput) -> Maif isinstance(result, ExistingReportMatch) and input.team_id is not None:report = await SignalReport.objects.filter(team_id=input.team_id, id=result.report_id).afirst()if report is not None and report.status != SignalReport.Status.DELETED:- current = await database_sync_to_async(latest_recurrence_report, thread_sensitive=False)(report)+ current = await database_sync_to_async(signal_target_report, thread_sensitive=False)(report)if current.id != report.id:result.report_id = str(current.id)unsafe = await database_sync_to_async(_is_safety_suppressed, thread_sensitive=False)(@@ -769,7 +770,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As# does, so this signal contradicts it and must not be absorbed. The other dismissal# codes state a preference about the report, and a sink is the right answer for# them (see recurrence.py).- report = latest_recurrence_report(report, lock=True)+ report = signal_target_report(report, lock=True)dismissed_as_fixed_at = (fixed_dismissal_at(report) if report.status == SignalReport.Status.SUPPRESSED else None)diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex 680669c0032d..dd70f7e84afd 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -21,6 +21,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.signal_metadata import (EMBEDDING_MODEL,+ REASSIGN_SIGNAL_ROW_CAP,SIGNAL_DOCUMENT_PRODUCT,SIGNAL_DOCUMENT_RENDERING,SIGNAL_DOCUMENT_TYPE,@@ -155,6 +156,50 @@ def soft_delete_report_signals(report_id: str, team_id: int, team: Team) -> None)+def reassign_report_signals(*, source_report_id: str, survivor_report_id: str, team_id: int, team: Team) -> int:+ """Re-emit a report's live ClickHouse signals under another report's id, and return how many.++ The same trick as `soft_delete_report_signals`: keep each row's `document_id` and timestamp so+ the re-emission replaces the original in its ReplacingMergeTree partition instead of adding a+ second copy. Only live rows move, because a deleted signal is already retracted from semantic+ search and moving it would resurrect it under the survivor.+ """+ result = execute_hogql_query(+ query_type="SignalsReassignForReport",+ query=_signals_for_report_query(limit=REASSIGN_SIGNAL_ROW_CAP),+ team=team,+ placeholders=_report_placeholders(source_report_id),+ )++ moved = 0+ for row in result.results or []:+ document_id, content, metadata_str, timestamp_raw, _inserted_at_raw = row+ metadata = json.loads(metadata_str)+ metadata["report_id"] = survivor_report_id++ emit_embedding_request(+ content=content,+ team_id=team_id,+ product=SIGNAL_DOCUMENT_PRODUCT,+ document_type=SIGNAL_DOCUMENT_TYPE,+ rendering=SIGNAL_DOCUMENT_RENDERING,+ document_id=document_id,+ models=[m.value for m in EmbeddingModelName],+ timestamp=_ensure_tz_aware(timestamp_raw),+ metadata=metadata,+ )+ moved += 1+ if moved >= REASSIGN_SIGNAL_ROW_CAP:+ logger.warning(+ "signals_reassign_hit_row_cap",+ team_id=team_id,+ source_report_id=source_report_id,+ survivor_report_id=survivor_report_id,+ moved=moved,+ )+ return moved++# ---------------------------------------------------------------------------# fetch_signal_type_examples_activity# ---------------------------------------------------------------------------diff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.pyindex 83aabe10bfa4..bbe9fcc186c5 100644--- a/products/signals/backend/test/test_assign_and_emit_signal.py+++ b/products/signals/backend/test/test_assign_and_emit_signal.py@@ -19,6 +19,7 @@ from products.signals.backend.daily_limit import DailyReportLimitGatefrom products.signals.backend.enums import ReportLinkKindfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.quota import SelfDrivingQuotaGate+from products.signals.backend.report_merge import MERGE_DISMISSAL_REASONfrom products.signals.backend.temporal.grouping import (WEIGHT_THRESHOLD,AssignAndEmitSignalInput,@@ -582,6 +583,32 @@ async def test_recurrence_forks_again_once_the_previous_fork_is_resolved(ateam):assert third.report_id == second.report_id[email protected]("dismissal_reason", [MERGE_DISMISSAL_REASON, "wontfix_intentional"])+async def test_signal_follows_a_merge_pointer_to_the_survivor(ateam, dismissal_reason):+ # A merged report keeps absorbing matches otherwise: its signals stay in the semantic index+ # under its own id until the re-emit lands, and a suppressed report accrues them silently.+ # Only a merge redirects. A hand-written `duplicate_of` on a report dismissed for any other+ # reason leaves it the sink it was.+ survivor = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam, status=SignalReport.Status.READY, title="survivor", summary="survivor summary"+ )+ source = await _suppressed_report(ateam, dismissal_reason)+ await database_sync_to_async(SignalReportArtefact.add_log)(+ team_id=ateam.id,+ report_id=str(source.id),+ content=ReportLink(kind=ReportLinkKind.DUPLICATE_OF, report_id=str(survivor.id)),+ attribution=ArtefactAttribution.system(),+ )++ result = await assign_and_emit_signal_activity(+ _build_input(ateam.id, _existing_match(str(source.id)), weight=WEIGHT_THRESHOLD)+ )++ assert result.report_id == str(survivor.id if dismissal_reason == MERGE_DISMISSAL_REASON else source.id)++@pytest.mark.asyncio@pytest.mark.django_db@pytest.mark.parametrize("link_kind", [None, ReportLinkKind.FOLLOW_UP_OF])diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 7d1c2978eb29..dd352e8bbfc7 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -5,6 +5,7 @@ from types import SimpleNamespacefrom typing import TYPE_CHECKING, castfrom urllib.parse import urlencode+import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -23,7 +24,7 @@ from social_django.models import UserSocialAuthfrom posthog.constants import AvailableFeaturefrom posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitErrorfrom posthog.egress.limiter.policies import Priority-from posthog.models import OAuthApplication+from posthog.models import OAuthApplication, Userfrom posthog.models.integration import GitHubIntegrationfrom posthog.models.team.team import Teamfrom posthog.models.user_integration import UserIntegration@@ -40,22 +41,35 @@ from products.access_control.backend.models.access_control import AccessControlfrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.actions.backend.models.action import Actionfrom products.event_definitions.backend.models.property_definition import PropertyDefinition-from products.signals.backend.artefact_schemas import ChannelAssignment+from products.signals.backend.artefact_schemas import (+ ChannelAssignment,+ Dismissal,+ NoteArtefact,+ PriorityAssessment,+ PullRequestLink,+ ReportLink,+)+from products.signals.backend.enums import ReportLinkKind, ReportPriorityfrom products.signals.backend.implementation_pr import (ImplementationPr,fetch_implementation_pr_state_for_reports,fetch_implementation_pr_urls_for_reports,+ implementation_pr_needed_by_another_report,)from products.signals.backend.models import (ArtefactAttribution,SignalReport,SignalReportArtefact,SignalReportAssignment,+ SignalReportPullRequest,SignalReportTask,SignalTeamConfig,SignalUserAutonomyConfig,)-from products.signals.backend.signal_metadata import ReportSignalMeta+from products.signals.backend.report_assignments import create_claim+from products.signals.backend.report_claims import get_active_claim+from products.signals.backend.report_merge import MERGE_DISMISSAL_REASON+from products.signals.backend.signal_metadata import REASSIGN_SIGNAL_ROW_CAP, ReportSignalMetafrom products.signals.backend.task_run_artefacts import (TASK_RUN_TYPE_IMPLEMENTATION,TASK_RUN_TYPE_RESEARCH,@@ -2773,6 +2787,233 @@ class TestSignalReportSuppressionAPI(APIBaseTest):assert report.summary == "Original summary"+class TestSignalReportMergeAPI(APIBaseTest):+ def _merge_url(self, report_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/merge/"++ def _state_url(self, report_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/state/"++ def _report(self, *, team=None, report_status=SignalReport.Status.READY, **kwargs) -> SignalReport:+ return SignalReport.objects.create(+ team=team or self.team,+ status=report_status,+ title=kwargs.pop("title", "A report"),+ summary=kwargs.pop("summary", "A summary"),+ **kwargs,+ )++ def _merge(self, survivor: SignalReport, *sources: SignalReport, reason: str | None = None):+ body: dict = {"source_report_ids": [str(source.id) for source in sources]}+ if reason is not None:+ body["reason"] = reason+ with self.captureOnCommitCallbacks(execute=False):+ return self.client.post(+ self._merge_url(str(survivor.id)), data=json.dumps(body), content_type="application/json"+ )++ def test_merge_moves_the_work_log_and_archives_the_source(self):+ survivor = self._report(signal_count=3, total_weight=1.5, corroboration_count=1)+ source = self._report(signal_count=2, total_weight=0.5, title="The twin", corroboration_count=4)+ SignalReportArtefact.add_log(+ team_id=self.team.id,+ report_id=str(source.id),+ content=NoteArtefact(note="research found the root cause"),+ attribution=ArtefactAttribution.system(),+ )+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=str(source.id),+ content=PriorityAssessment(priority=ReportPriority.P0, explanation="the source thought it urgent"),+ attribution=ArtefactAttribution.system(),+ )++ response = self._merge(survivor, source, reason="same support ticket")+ assert response.status_code == status.HTTP_200_OK, response.json()++ payload = response.json()+ assert payload["sources"] == [+ {"id": str(source.id), "artefacts_moved": 1, "signals_moved": 2, "released_claim": False}+ ]+ # The response renders the survivor as it stands after the merge, counters included.+ assert (payload["report"]["id"], payload["report"]["signal_count"]) == (str(survivor.id), 5)++ survivor.refresh_from_db()+ source.refresh_from_db()+ assert survivor.signal_count == 5+ assert survivor.total_weight == pytest.approx(2.0)+ # Corroborations past the per-report note cap have no artefact rows, only this counter.+ assert survivor.corroboration_count == 5+ # The source keeps its counters as the record of what it collected.+ assert (source.signal_count, source.status) == (2, SignalReport.Status.SUPPRESSED)++ moved = SignalReportArtefact.objects.filter(report_id=survivor.id, type="note").values_list(+ "content", flat=True+ )+ assert any("root cause" in content for content in moved)+ # A status artefact is latest-wins, so moving it would override the survivor's own verdict.+ assert SignalReportArtefact.objects.filter(report_id=survivor.id, type="priority_judgment").count() == 0+ assert SignalReportArtefact.objects.filter(report_id=source.id, type="priority_judgment").count() == 1++ link = SignalReportArtefact.objects.get(report_id=source.id, type="report_link")+ parsed = ReportLink.model_validate_json(link.content)+ assert (parsed.kind, parsed.report_id, parsed.reason) == (+ ReportLinkKind.DUPLICATE_OF,+ str(survivor.id),+ "same support ticket",+ )+ dismissal = SignalReportArtefact.objects.get(report_id=source.id, type="dismissal")+ assert Dismissal.model_validate_json(dismissal.content).reason == MERGE_DISMISSAL_REASON++ def test_merge_moves_the_pull_request_so_the_dismissal_leaves_it_open(self):+ survivor = self._report()+ source = self._report()+ pr = SignalReportPullRequest.objects.create(+ team=self.team,+ repository="posthog/posthog",+ number=4242,+ url="https://github.com/PostHog/posthog/pull/4242",+ )+ artefact = SignalReportArtefact.add_log(+ team_id=self.team.id,+ report_id=str(source.id),+ content=PullRequestLink(url=pr.url),+ attribution=ArtefactAttribution.system(),+ )+ SignalReportArtefact.objects.filter(id=artefact.id).update(pull_request=pr)++ assert self._merge(survivor, source).status_code == status.HTTP_200_OK++ assert SignalReportArtefact.objects.get(id=artefact.id).report_id == survivor.id+ assert implementation_pr_needed_by_another_report(team_id=self.team.id, report_id=str(source.id), pr_url=pr.url)++ @parameterized.expand([("another_actor", False), ("the_caller", True)])+ def test_merge_releases_the_sources_claim_whoever_holds_it(self, _name, caller_owns):+ # Claim history stays on the source, so a claim left active there would make the survivor+ # look unclaimed while the work is still owned, and another actor could take it.+ survivor = self._report()+ source = self._report()+ if caller_owns:+ owner = self.user+ else:+ owner = User.objects.create_and_join(self.organization, "[email protected]", None)+ create_claim(source, ArtefactAttribution.from_user(owner.id))++ response = self._merge(survivor, source)+ assert response.status_code == status.HTTP_200_OK, response.json()++ assert response.json()["sources"][0]["released_claim"] is True+ assert get_active_claim(team_id=self.team.id, report_id=str(source.id)) is None+ assert get_active_claim(team_id=self.team.id, report_id=str(survivor.id)) is None++ @parameterized.expand(+ [+ # A resolved report is terminal for new signals, so the sources' signals would land+ # somewhere the pipeline never looks again while the sources archive for good. A+ # suppressed one is not visible to this action at all.+ ("resolved", SignalReport.Status.RESOLVED, status.HTTP_409_CONFLICT),+ ("suppressed", SignalReport.Status.SUPPRESSED, status.HTTP_404_NOT_FOUND),+ ]+ )+ def test_merge_refuses_a_survivor_that_is_not_live(self, _name, survivor_status, expected_code):+ survivor = self._report(report_status=survivor_status, signal_count=3)+ source = self._report(signal_count=2)++ assert self._merge(survivor, source).status_code == expected_code++ source.refresh_from_db()+ survivor.refresh_from_db()+ assert source.status == SignalReport.Status.READY+ assert survivor.signal_count == 3++ @parameterized.expand(+ [+ ("self_merge", "self", "cannot be merged into itself"),+ ("resolved_source", SignalReport.Status.RESOLVED, "cannot be merged"),+ ("suppressed_source", SignalReport.Status.SUPPRESSED, "cannot be merged"),+ # A research run is writing to an in-progress report, and `SUPPRESSED -> READY` is+ # legal, so the run would resurrect it after the merge moved its work away.+ ("in_progress_source", SignalReport.Status.IN_PROGRESS, "cannot be merged"),+ ("oversized_source", "oversized", "too large to merge"),+ ("other_team_source", "other_team", "was not found"),+ ]+ )+ def test_merge_refuses_a_source_it_cannot_fold_in(self, _name, source_spec, expected_error):+ survivor = self._report(signal_count=3)+ if source_spec == "self":+ source = survivor+ elif source_spec == "other_team":+ other_team = Team.objects.create(organization=self.organization, name="Other")+ source = self._report(team=other_team)+ elif source_spec == "oversized":+ source = self._report(signal_count=REASSIGN_SIGNAL_ROW_CAP + 1)+ else:+ source = self._report(report_status=source_spec)++ response = self._merge(survivor, source)++ assert response.status_code == status.HTTP_409_CONFLICT, response.json()+ assert expected_error in response.json()["error"]+ survivor.refresh_from_db()+ assert survivor.signal_count == 3++ def test_one_bad_source_leaves_the_whole_merge_unapplied(self):+ survivor = self._report(signal_count=1)+ good = self._report(signal_count=2)+ bad = self._report(signal_count=4, report_status=SignalReport.Status.RESOLVED)++ assert self._merge(survivor, good, bad).status_code == status.HTTP_409_CONFLICT++ survivor.refresh_from_db()+ good.refresh_from_db()+ assert survivor.signal_count == 1+ assert good.status == SignalReport.Status.READY++ @parameterized.expand([("straight_after_the_merge", False), ("after_a_later_dismissal", True)])+ def test_a_merged_report_cannot_be_restored(self, _name, dismiss_again):+ survivor = self._report()+ source = self._report()+ assert self._merge(survivor, source).status_code == status.HTTP_200_OK+ if dismiss_again:+ # A merge is structural, not a verdict: the signals and work log are on the survivor+ # either way, so a newer dismissal must not make the source restorable.+ assert (+ self.client.post(+ self._state_url(str(source.id)),+ data=json.dumps({"state": "suppressed", "dismissal_reason": "wontfix_irrelevant"}),+ content_type="application/json",+ ).status_code+ == status.HTTP_200_OK+ )++ response = self.client.post(+ self._state_url(str(source.id)), data=json.dumps({"state": "potential"}), content_type="application/json"+ )++ assert response.status_code == status.HTTP_409_CONFLICT, response.json()+ source.refresh_from_db()+ assert source.status == SignalReport.Status.SUPPRESSED++ def test_merge_schedules_the_signal_move_once_committed(self):+ survivor = self._report()+ source = self._report()++ with patch("products.signals.backend.tasks.move_merged_report_signals.delay") as move:+ with self.captureOnCommitCallbacks(execute=True):+ assert (+ self.client.post(+ self._merge_url(str(survivor.id)),+ data=json.dumps({"source_report_ids": [str(source.id)]}),+ content_type="application/json",+ ).status_code+ == status.HTTP_200_OK+ )++ move.assert_called_once_with(+ team_id=self.team.id, survivor_report_id=str(survivor.id), source_report_ids=[str(source.id)]+ )++class TestAvailableReviewersAPI(APIBaseTest):"""GET signals/reports/available_reviewers/: returns every eligible org member (no cap), with server-side search."""diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex dfd85dddb2cb..faf4b27ceeca 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -144,6 +144,13 @@ from products.signals.backend.report_generation.resolve_reviewers import (source_skills_from_suggested_reviewer_artefacts,)from products.signals.backend.report_generation.reviewer_telemetry import capture_suggested_reviewers_resolved+from products.signals.backend.report_merge import (+ MAX_MERGE_REASON_LENGTH,+ MAX_MERGE_SOURCE_REPORTS,+ ReportMergeError,+ merge_reports,+ was_merged_away,+)from products.signals.backend.report_metric_access import ReportMetricAccessPolicyfrom products.signals.backend.report_metric_refresh import CURRENT_REPORT_STATUSES, refresh_report_metric_snapshotsfrom products.signals.backend.reviewer_correction_notes import ReviewerCorrection, forward_reviewer_correction_note@@ -734,6 +741,59 @@ class SignalReportBulkStateResponseSerializer(serializers.Serializer):not_found_count = serializers.IntegerField(help_text="Number of requested ids not visible to the caller.")+class SignalReportMergeRequestSerializer(serializers.Serializer):+ source_report_ids = serializers.ListField(+ child=serializers.UUIDField(),+ allow_empty=False,+ # min_length (not just allow_empty=False) so the non-empty constraint surfaces as+ # `minItems: 1` in the generated OpenAPI/Zod schema, not only as a server-side 400.+ min_length=1,+ max_length=MAX_MERGE_SOURCE_REPORTS,+ help_text=(+ "Ids of the duplicate reports to fold into this one (1–"+ f"{MAX_MERGE_SOURCE_REPORTS}). Each must be a live report in this project: a resolved, "+ "archived or deleted report is rejected with 409, as is the survivor's own id. "+ "Duplicates in the list are de-duplicated. The whole merge applies or none of it does."+ ),+ )+ reason = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=MAX_MERGE_REASON_LENGTH,+ help_text=(+ "Optional one-line explanation of why these reports are the same issue. Recorded on "+ "each source's 'duplicate of' link and on the note left on the survivor. Capped at "+ f"{MAX_MERGE_REASON_LENGTH} characters."+ ),+ )+++class SignalReportMergeSourceResultSerializer(serializers.Serializer):+ id = serializers.UUIDField(source="report_id", help_text="The source report that was folded into the survivor.")+ artefacts_moved = serializers.IntegerField(+ help_text=(+ "How many work-log artefacts moved to the survivor (notes, findings, pull requests, "+ "task runs, code references, commits, checks)."+ )+ )+ signals_moved = serializers.IntegerField(+ help_text=(+ "How many signals the survivor took on from this source. The signals themselves are "+ "re-pointed asynchronously; the survivor's counters already include them."+ )+ )+ released_claim = serializers.BooleanField(+ help_text="Whether an active work claim held by another actor was released before the move."+ )+++class SignalReportMergeResponseSerializer(serializers.Serializer):+ report = SignalReportSerializer(help_text="The surviving report, as it stands after the merge.")+ sources = SignalReportMergeSourceResultSerializer(+ many=True, help_text="One result per merged source, in request order (after de-duplication)."+ )++# The thumbs rating at the end of the report body carries an optional note, capped in the UI at the# same length as the dismissal note.SIGNAL_REPORT_FEEDBACK_NOTE_MAX_LENGTH = SIGNAL_REPORT_DISMISSAL_NOTE_MAX_LENGTH@@ -2392,6 +2452,82 @@ class SignalReportViewSet(return Response(SignalReportSerializer(report, context=self._enriched_report_context(report)).data)+ @validated_request(+ request_serializer=SignalReportMergeRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=SignalReportMergeResponseSerializer,+ description="The surviving report after the merge, plus one result per merged source.",+ ),+ 404: OpenApiResponse(description="The surviving report was not found in this project."),+ 409: OpenApiResponse(+ description=(+ "Both ends of a merge must be a live report of this project. Returned when "+ "the survivor is resolved, or when a source is the survivor itself, is resolved "+ "or archived, is still being researched, carries more signals than one merge "+ "can move, or belongs to another project. Nothing is applied."+ )+ ),+ },+ summary="Merge duplicate reports into this one",+ description=(+ "Fold one or more duplicate reports into this report, which survives. The sources' "+ "signals, work-log artefacts, pull requests, task runs and checks move onto the "+ "survivor, the survivor's signal counters take on theirs, and each source is archived "+ "with a 'duplicate of' link back to the survivor. A source's open pull request stays "+ "open, because the survivor holds it after the move. Pick the survivor deliberately: "+ "prefer the older report, and prefer the one with an open implementation PR or an "+ "active claim. Any active claim on a source is released, so re-claim the survivor if "+ "you were working on one. Titles and summaries are not combined, so edit it afterwards "+ "if it needs a rewrite. A merged report keeps its URL but cannot be restored, because "+ "its signals now belong to the survivor."+ ),+ operation_id="signals_reports_merge_create",+ )+ @action(detail=True, methods=["post"], url_path="merge", required_scopes=["task:write"])+ def merge(self, request: ValidatedRequest, pk=None, **kwargs):+ survivor = cast(SignalReport, self.get_object())+ data = request.validated_data+ # Resolved before the merge transaction, so a bad X-PostHog-Task-Id header 400s before+ # anything moves (the same rule as the refund and artefact write paths).+ attribution = resolve_request_attribution(request, self.team.id)++ try:+ result = merge_reports(+ team=self.team,+ survivor=survivor,+ source_ids=[str(source_id) for source_id in data["source_report_ids"]],+ attribution=attribution,+ reason=(data.get("reason") or "").strip() or None,+ )+ except ReportMergeError as e:+ return Response({"error": e.detail}, status=status.HTTP_409_CONFLICT)++ report_user_action(+ request.user,+ "signals_report_merged",+ properties={+ "team_id": self.team.id,+ "organization_id": str(self.organization.id),+ "report_id": result.survivor_id,+ "actor_kind": attribution.kind,+ "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),+ },+ team=self.team,+ organization=self.organization,+ request=request,+ )++ survivor.refresh_from_db()+ return Response(+ SignalReportMergeResponseSerializer(+ {"report": survivor, "sources": result.sources},+ context=self._enriched_report_context(survivor),+ ).data+ )+@extend_schema(summary="Leave feedback on a report",description=(@@ -2732,6 +2868,15 @@ class SignalReportViewSet(SignalReportBulkStateOutcome.SKIPPED,"This report is archived. Refresh it before continuing.",)+ # A merged report has no signals of its own left: they moved to the survivor, and+ # so did its work log. Restoring it would put an empty duplicate back in the inbox+ # and start it collecting again alongside the report it was folded into.+ if was_merged_away(report):+ return (+ SignalReportBulkStateOutcome.SKIPPED,+ "This report was merged into another one and can't be restored. Open the report it was "+ "merged into instead.",+ )effective_target = report.restore_target_status()effective_snooze_for = snooze_for if target == "potential" else Nonediff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 0964d3d80c05..1b07b79a1d0b 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -782,6 +782,38 @@ export interface SignalReportFeedbackResponseApi {forwarded: boolean}+export interface SignalReportMergeRequestApi {+ /**+ * Ids of the duplicate reports to fold into this one (1–10). Each must be a live report in this project: a resolved, archived or deleted report is rejected with 409, as is the survivor's own id. Duplicates in the list are de-duplicated. The whole merge applies or none of it does.+ * @minItems 1+ * @maxItems 10+ */+ source_report_ids: string[]+ /**+ * Optional one-line explanation of why these reports are the same issue. Recorded on each source's 'duplicate of' link and on the note left on the survivor. Capped at 500 characters.+ * @maxLength 500+ */+ reason?: string+}++export interface SignalReportMergeSourceResultApi {+ /** The source report that was folded into the survivor. */+ id: string+ /** How many work-log artefacts moved to the survivor (notes, findings, pull requests, task runs, code references, commits, checks). */+ artefacts_moved: number+ /** How many signals the survivor took on from this source. The signals themselves are re-pointed asynchronously; the survivor's counters already include them. */+ signals_moved: number+ /** Whether an active work claim held by another actor was released before the move. */+ released_claim: boolean+}++export interface SignalReportMergeResponseApi {+ /** The surviving report, as it stands after the merge. */+ report: SignalReportApi+ /** One result per merged source, in request order (after de-duplication). */+ sources: SignalReportMergeSourceResultApi[]+}+/*** One CI check on a pull request's head commit — a GitHub Actions check run or a legacy commit* status, normalized to a common shape.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 88e828f380a8..62b8e69d35d5 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -74,6 +74,8 @@ import type {SignalReportClaimApi,SignalReportFeedbackRequestApi,SignalReportFeedbackResponseApi,+ SignalReportMergeRequestApi,+ SignalReportMergeResponseApi,SignalReportMetricRefreshRequestApi,SignalReportMetricRefreshResponseApi,SignalReportRefundRequestApi,@@ -311,6 +313,28 @@ export const signalsReportsFeedbackCreate = async (})}+export const getSignalsReportsMergeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/reports/${id}/merge/`+}++/**+ * Fold one or more duplicate reports into this report, which survives. The sources' signals, work-log artefacts, pull requests, task runs and checks move onto the survivor, the survivor's signal counters take on theirs, and each source is archived with a 'duplicate of' link back to the survivor. A source's open pull request stays open, because the survivor holds it after the move. Pick the survivor deliberately: prefer the older report, and prefer the one with an open implementation PR or an active claim. Any active claim on a source is released, so re-claim the survivor if you were working on one. Titles and summaries are not combined, so edit it afterwards if it needs a rewrite. A merged report keeps its URL but cannot be restored, because its signals now belong to the survivor.+ * @summary Merge duplicate reports into this one+ */+export const signalsReportsMergeCreate = async (+ projectId: string,+ id: string,+ signalReportMergeRequestApi: SignalReportMergeRequestApi,+ options?: RequestInit+): Promise<SignalReportMergeResponseApi> => {+ return apiMutator<SignalReportMergeResponseApi>(getSignalsReportsMergeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(signalReportMergeRequestApi),+ })+}+export const getSignalsReportPrChecksUrl = (projectId: string, id: string, params?: SignalsReportPrChecksParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 54a2676cde0f..e86637e772c3 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -102,6 +102,31 @@ export const SignalsReportsFeedbackCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Fold one or more duplicate reports into this report, which survives. The sources' signals, work-log artefacts, pull requests, task runs and checks move onto the survivor, the survivor's signal counters take on theirs, and each source is archived with a 'duplicate of' link back to the survivor. A source's open pull request stays open, because the survivor holds it after the move. Pick the survivor deliberately: prefer the older report, and prefer the one with an open implementation PR or an active claim. Any active claim on a source is released, so re-claim the survivor if you were working on one. Titles and summaries are not combined, so edit it afterwards if it needs a rewrite. A merged report keeps its URL but cannot be restored, because its signals now belong to the survivor.+ * @summary Merge duplicate reports into this one+ */+export const signalsReportsMergeCreateBodySourceReportIdsMax = 10++export const signalsReportsMergeCreateBodyReasonMax = 500++export const SignalsReportsMergeCreateBody = /* @__PURE__ */ zod.object({+ source_report_ids: zod+ .array(zod.uuid())+ .min(1)+ .max(signalsReportsMergeCreateBodySourceReportIdsMax)+ .describe(+ "Ids of the duplicate reports to fold into this one (1–10). Each must be a live report in this project: a resolved, archived or deleted report is rejected with 409, as is the survivor's own id. Duplicates in the list are de-duplicated. The whole merge applies or none of it does."+ ),+ reason: zod+ .string()+ .max(signalsReportsMergeCreateBodyReasonMax)+ .optional()+ .describe(+ "Optional one-line explanation of why these reports are the same issue. Recorded on each source's 'duplicate of' link and on the note left on the survivor. Capped at 500 characters."+ ),+})+/*** Post an inline review comment on the report's implementation pull request, attributed to the requesting user's own GitHub identity via their personal GitHub connection. Either replies to an existing thread (`in_reply_to`) or starts a new thread on a diff line (`path` + `line`).* @summary Post an inline review comment on a report's implementation PRdiff --git a/products/signals/frontend/inbox/utils/dismissalReasons.ts b/products/signals/frontend/inbox/utils/dismissalReasons.tsindex a0b0660a501a..b599bced58ea 100644--- a/products/signals/frontend/inbox/utils/dismissalReasons.ts+++ b/products/signals/frontend/inbox/utils/dismissalReasons.ts@@ -74,9 +74,11 @@ export function suppressDismissalPayload(dismissal: DismissalFeedback): {// Reason codes persisted by flows outside the two dialogs (never user-selectable there), so the// reason chip still renders a label instead of the raw code. `refunded` is written by the PR-// refund action, which dismisses the report as part of the refund.+// refund action, which dismisses the report as part of the refund. `merged` is written by the+// report merge action, which archives each duplicate it folds into the surviving report.const EXTRA_DISMISSAL_REASON_LABELS: Record<string, string> = {refunded: 'Refunded',+ merged: 'Merged into another report',}/** Human label for a persisted reason code, or the raw code if it's not a known option. */diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 8f2094b24e8f..898384ec64e2 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -285,6 +285,35 @@ tools:- assignee- created_at- updated_at+ inbox-reports-merge:+ operation: signals_reports_merge_create+ enabled: false+ scopes:+ - task:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: false+ enrich_url: '{id}'+ title: Merge duplicate reports into one+ description: >+ Fold duplicate inbox reports into the one report that survives them, when the same issue landed in more than+ one report. The URL names the survivor and `source_report_ids` (1–10) names the duplicates. Pick the+ survivor deliberately: prefer the older report, and prefer the one holding an open implementation PR or an+ active claim. The sources' signals, work-log artefacts, pull requests, task runs and checks move onto the+ survivor, the survivor's signal counters take theirs on, and each source is archived with a 'duplicate of'+ link back. A source's open pull request stays open, because the survivor holds it after the move; any active+ claim on a source is released first, so re-claim the survivor if you were working on one. Titles and+ summaries are NOT combined, so follow with `inbox-reports-update` if the survivor needs a rewrite. Both ends+ must be a live report, and the whole call applies or none of it does: 409 and no writes when the survivor is+ resolved, or when a source is the survivor itself, is resolved or archived, is still being researched+ (`in_progress`), or carries more signals than one merge can move. A merged report keeps its URL but can+ never be restored, so merge only reports you are confident are the same issue, and use an+ `inbox-report-artefacts-create` `related_to` link when they are merely related.+ param_overrides:+ id:+ aliases:+ - survivor_report_idinbox-reports-retrieve:operation: signals_reports_retrieveenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3ad73ac232a1..5e1aac663bdd 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -86841,6 +86841,38 @@ export namespace Schemas {forwarded: boolean;}+ export interface SignalReportMergeRequest {+ /**+ * Ids of the duplicate reports to fold into this one (1–10). Each must be a live report in this project: a resolved, archived or deleted report is rejected with 409, as is the survivor's own id. Duplicates in the list are de-duplicated. The whole merge applies or none of it does.+ * @minItems 1+ * @maxItems 10+ */+ source_report_ids: string[];+ /**+ * Optional one-line explanation of why these reports are the same issue. Recorded on each source's 'duplicate of' link and on the note left on the survivor. Capped at 500 characters.+ * @maxLength 500+ */+ reason?: string;+ }++ export interface SignalReportMergeSourceResult {+ /** The source report that was folded into the survivor. */+ id: string;+ /** How many work-log artefacts moved to the survivor (notes, findings, pull requests, task runs, code references, commits, checks). */+ artefacts_moved: number;+ /** How many signals the survivor took on from this source. The signals themselves are re-pointed asynchronously; the survivor's counters already include them. */+ signals_moved: number;+ /** Whether an active work claim held by another actor was released before the move. */+ released_claim: boolean;+ }++ export interface SignalReportMergeResponse {+ /** The surviving report, as it stands after the merge. */+ report: SignalReport;+ /** One result per merged source, in request order (after de-duplication). */+ sources: SignalReportMergeSourceResult[];+ }+export interface SignalReportMetricRefreshRequest {/*** Reports on screen, in display order. Each report's row metric is refreshed before any report's supporting metrics. At most 20 ids per call.