: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): surface legacy SignalReportTask rows in the artefact list (#65504)
Oliver Browne194fb0389f28
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex d97335dfdfcf..e6364b7b11ed 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -513,6 +513,54 @@ class SignalReport(UUIDModel):result[report_id] = runsreturn result+ @classmethod+ def synthetic_legacy_task_run_artefacts(+ cls, *, report_id: str, team_id: int, existing_artefacts: "list[SignalReportArtefact]"+ ) -> "list[SignalReportArtefact]":+ """Unsaved `task_run` artefacts standing in for legacy `SignalReportTask` rows whose task is+ not yet represented in the artefact log, so a report's research / implementation /+ repo-selection associations surface in the artefact list even before+ `backfill_task_run_artefacts` has converted its gate rows.++ De-duplicated by task against the `task_run` artefacts already in `existing_artefacts` (a+ real row always wins); each synthetic row borrows its `SignalReportTask` id and `created_at`+ so it is stable across polls and chronologically correct, and applies the same+ `(product, type)` mapping the backfill would. Never saved — the backfill is what persists+ them for real; this is the read-time view of that union (the row-level counterpart of+ `associated_task_runs`).+ """+ seen_task_ids: set[str] = set()+ for artefact in existing_artefacts:+ if artefact.type != SignalReportArtefact.ArtefactType.TASK_RUN:+ continue+ try:+ seen_task_ids.add(TaskRunArtefact.model_validate_json(artefact.content).task_id)+ except ValidationError:+ continue++ synthetic: list[SignalReportArtefact] = []+ report_tasks = SignalReportTask.objects.filter(report_id=report_id, team_id=team_id).order_by("created_at")+ for report_task in report_tasks:+ task_id = str(report_task.task_id)+ if task_id in seen_task_ids:+ continue+ seen_task_ids.add(task_id)+ product, run_type = task_run_identifier_for_legacy_relationship(report_task.relationship)+ synthetic.append(+ SignalReportArtefact(+ id=report_task.id,+ team_id=team_id,+ report_id=report_id,+ type=SignalReportArtefact.ArtefactType.TASK_RUN,+ content=TaskRunArtefact(+ task_id=task_id, run_id=None, product=product, type=run_type+ ).model_dump_json(),+ created_at=report_task.created_at,+ task_id=report_task.task_id,+ )+ )+ return synthetic+@staticmethoddef associated_task_runs_filter(report_ref: Any) -> "models.Q":"""A `Q` matching `tasks.TaskRun`s whose task is associated with the correlated report,diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex c65a83d8feb2..19a79d31f7a5 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -1779,3 +1779,125 @@ class TestSignalReportTaskAssociationViaArtefacts(APIBaseTest):def test_reports_list_rejects_malformed_task_id(self):response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/?task_id=not-a-uuid")assert response.status_code == status.HTTP_400_BAD_REQUEST+++class TestSignalReportLegacyTaskArtefactList(APIBaseTest):+ """The artefact list surfaces legacy `SignalReportTask` rows as synthetic `task_run` artefacts so+ research / implementation associations show up before the backfill has converted the gate rows."""++ def _artefacts_url(self, report_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/artefacts/"++ def _create_report(self, team=None) -> SignalReport:+ return SignalReport.objects.create(+ team=team or self.team,+ status=SignalReport.Status.READY,+ title="Report",+ summary="Summary",+ signal_count=1,+ total_weight=1.0,+ )++ def _create_task(self, team=None) -> "Task":+ Task = apps.get_model("tasks", "Task")+ return Task.objects.create(+ team=team or self.team,+ title="task",+ description="desc",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )++ def _task_runs(self, report_id: str) -> list[dict]:+ response = self.client.get(self._artefacts_url(report_id))+ assert response.status_code == status.HTTP_200_OK, response.json()+ return [a for a in response.json()["results"] if a["type"] == "task_run"]++ @parameterized.expand(+ [+ ("research", "signals", "research"),+ ("implementation", "signals", "implementation"),+ ("repo_selection", "signals", "repo_selection"),+ (None, "tasks", "agent_run"),+ ("link-only", "tasks", "agent_run"),+ ]+ )+ def test_legacy_task_surfaces_as_synthetic_task_run(self, relationship, expected_product, expected_type):+ report = self._create_report()+ task = self._create_task()+ report_task = SignalReportTask.objects.create(+ team=self.team, report=report, task=task, relationship=relationship+ )++ task_runs = self._task_runs(str(report.id))+ assert len(task_runs) == 1+ artefact = task_runs[0]+ assert artefact["id"] == str(report_task.id)+ assert str(artefact["task_id"]) == str(task.id)+ assert artefact["content"]["task_id"] == str(task.id)+ assert artefact["content"]["product"] == expected_product+ assert artefact["content"]["type"] == expected_type++ def test_real_task_run_artefact_wins_over_legacy_row(self):+ report = self._create_report()+ task = self._create_task()+ # Both the gate row and the real artefact exist for the same task: only the real one shows.+ SignalReportTask.objects.create(team=self.team, report=report, task=task, relationship="implementation")+ append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product="signals",+ type="implementation",+ task_id=str(task.id),+ )++ task_runs = self._task_runs(str(report.id))+ assert len(task_runs) == 1+ # The persisted artefact id is a real row, not the gate row's id.+ assert SignalReportArtefact.objects.filter(id=task_runs[0]["id"]).exists()++ def test_legacy_rows_are_not_persisted(self):+ report = self._create_report()+ task = self._create_task()+ SignalReportTask.objects.create(team=self.team, report=report, task=task, relationship="research")++ self._task_runs(str(report.id))+ # Listing must not write the synthetic artefacts — the backfill owns that.+ assert not SignalReportArtefact.objects.filter(report=report).exists()++ def test_synthetic_rows_count_and_interleave_chronologically(self):+ report = self._create_report()+ older_task = self._create_task()+ newer_task = self._create_task()+ # A real artefact dated between the two legacy rows, so a correct merge interleaves by time.+ older = SignalReportTask.objects.create(team=self.team, report=report, task=older_task, relationship="research")+ SignalReportTask.objects.filter(id=older.id).update(created_at=timezone.now() - timedelta(hours=2))+ middle = append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product="signals",+ type="repo_selection",+ task_id=str(self._create_task().id),+ )+ SignalReportArtefact.objects.filter(id=middle.id).update(created_at=timezone.now() - timedelta(hours=1))+ newer = SignalReportTask.objects.create(+ team=self.team, report=report, task=newer_task, relationship="implementation"+ )++ response = self.client.get(self._artefacts_url(str(report.id)))+ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ # count covers the real artefact plus both synthetic legacy rows.+ assert body["count"] == 3+ # Default order is newest-first; the legacy rows land at their own timestamps, not appended last.+ ids_newest_first = [a["id"] for a in body["results"]]+ assert ids_newest_first == [str(newer.id), str(middle.id), str(older.id)]++ def test_legacy_rows_do_not_cross_reports(self):+ report = self._create_report()+ other_report = self._create_report()+ task = self._create_task()+ SignalReportTask.objects.create(team=self.team, report=other_report, task=task, relationship="research")++ # The gate row belongs to `other_report`, so `report`'s log stays empty.+ assert self._task_runs(str(report.id)) == []+ assert len(self._task_runs(str(other_report.id))) == 1diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex c5562fe8bfa2..b335c27cfbe8 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -1479,8 +1479,24 @@ class SignalReportArtefactViewSet(def list(self, request, *args, **kwargs):queryset = self.filter_queryset(self.get_queryset())- page = self.paginate_queryset(queryset)- artefacts = list(page if page is not None else queryset)+ # Surface legacy `SignalReportTask` associations as synthetic `task_run` artefacts so a+ # report's research / implementation runs appear in the log even before the backfill has+ # converted its gate rows. Merged into the materialized log (de-duplicated against the real+ # task_run artefacts) and re-sorted newest-first so each legacy row lands at its original+ # timestamp, then paginated as one list so `count` and ordering both account for them.+ real_artefacts = list(queryset)+ synthetic = SignalReport.synthetic_legacy_task_run_artefacts(+ report_id=self.parents_query_dict["report_id"],+ team_id=self.team.id,+ existing_artefacts=real_artefacts,+ )+ log = (+ sorted([*real_artefacts, *synthetic], key=lambda a: a.created_at, reverse=True)+ if synthetic+ else real_artefacts+ )+ page = self.paginate_queryset(log)+ artefacts = list(page if page is not None else log)logins_union = normalized_github_logins_from_suggested_reviewer_artefacts(artefacts)login_map = resolve_org_github_login_to_users(self.team.id, logins_union) if logins_union else {}serializer = SignalReportArtefactSerializer(