: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(tasks): expose the latest run's pull request in task summaries (#99685)
Paul D'Ambra75f0530ecbd7
diff --git a/docs/internal/task-summaries.md b/docs/internal/task-summaries.mdnew file mode 100644index 000000000000..8a920c27504d--- /dev/null+++ b/docs/internal/task-summaries.md@@ -0,0 +1,22 @@+# Task summaries++`POST /api/projects/{project_id}/tasks/summaries/` returns summaries for the requested task IDs.+The response is paginated. Follow `next` with the same request body to load the remaining summaries.+Task visibility and project boundaries apply to every request.++`latest_run` is null when a task has no runs. Otherwise, it includes two nullable PR fields:++- `pr_url`: the PR URL recorded in the latest run, or null when no non-empty string URL is recorded.+- `pr_state`: `open`, `draft`, `closed`, `merged`, or `unknown`. This field is null when `pr_url` is null.++The run's `pr_merged` flag takes precedence over its recorded `pr_state`.+A PR with a missing or unrecognized state returns `unknown`.+The response excludes other run output, including generated summaries.+These fields describe the latest run only. They do not include PRs from earlier runs.++The batch query selects these fields with the run status. It does not load each run separately.+Each request reads current stored output. PR output can change without a change to the task's `updated_at` value.+The endpoint does not fetch live state from GitHub.++Deploy this backend change before a client relies on the new fields.+Clients that support older servers must retain their task-detail fallback when the PR fields are absent.diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 7a6dce29343d..63035c876495 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -3,7 +3,7 @@ import timeimport hashlibimport loggingfrom collections import Counter-from collections.abc import Collection, Iterable, Sequence+from collections.abc import Collection, Iterable, Mapping, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta@@ -37,7 +37,7 @@ from django.db.models import (Value,When,)-from django.db.models.fields.json import KeyTextTransform+from django.db.models.fields.json import KeyTextTransform, KeyTransformfrom django.db.models.functions import Coalescefrom django.utils import timezone as django_timezonefrom django.utils.http import content_disposition_header@@ -987,6 +987,15 @@ def get_tasks_by_ids(task_ids: Iterable[str | UUID], team_ids: Iterable[int]) ->return [_task_to_dto(task) for task in Task.objects.filter(id__in=ids, team_id__in=teams)]+def _pull_request_state(output: Mapping[str, object]) -> str:+ """The state of the PR in ``output.pr_url``. ``pr_merged`` wins over ``pr_state``: it is the+ webhook-attested flag, and runs merged before ``pr_state`` existed only carry it."""+ if output.get("pr_merged"):+ return "merged"+ state = output.get("pr_state")+ return state if isinstance(state, str) and state in PR_STATES else "unknown"++def get_pull_requests_for_tasks(team_id: int, task_ids: Iterable[str | UUID], *conditions: Q) -> dict[str, list[contracts.TaskPullRequest]]:@@ -1008,12 +1017,8 @@ def get_pull_requests_for_tasks(if key in seen:continueseen.add(key)- state = "unknown"- if url == output.get("pr_url"):- state = "merged" if output.get("pr_merged") else output.get("pr_state", "unknown")- result.setdefault(str(task_id), []).append(- contracts.TaskPullRequest(url=url, state=state if isinstance(state, str) else "unknown")- )+ state = _pull_request_state(output) if url == output.get("pr_url") else "unknown"+ result.setdefault(str(task_id), []).append(contracts.TaskPullRequest(url=url, state=state))return result@@ -5693,11 +5698,16 @@ def _search_latest_run_summary(run: TaskRun | None) -> contracts.TaskLatestRunSuif run is None:return Noneinteractive = (run.state or {}).get("mode") == "interactive"+ output = run.output if isinstance(run.output, dict) else {}+ pr_url = output.get("pr_url")+ pr_url = pr_url if isinstance(pr_url, str) and pr_url else Nonereturn contracts.TaskLatestRunSummaryDTO(id=run.id,status=run.status,environment=run.environment,mode="interactive" if interactive else "background",+ pr_url=pr_url,+ pr_state=_pull_request_state(output) if pr_url else None,)@@ -5801,6 +5811,21 @@ def list_task_repositories(team_id: int, user_id: int | None) -> list[str]:return sorted(set(plural) | {repository for repository in legacy if repository})+def _latest_run_summary(raw: object) -> contracts.TaskLatestRunSummaryDTO | None:+ if not isinstance(raw, dict):+ return None+ pr_url = raw.get("pr_url")+ pr_url = pr_url if isinstance(pr_url, str) and pr_url else None+ return contracts.TaskLatestRunSummaryDTO(+ id=raw["id"],+ status=raw.get("status"),+ environment=raw.get("environment"),+ mode=raw.get("mode", "background"),+ pr_url=pr_url,+ pr_state=_pull_request_state(raw) if pr_url else None,+ )++def get_task_summaries(team_id: int, user_id: int | None, *, ids: list) -> list[contracts.TaskSummaryDTO]:"""Summary fields for the requested tasks, mirroring ``TaskViewSet.summaries``."""from django.db.models.functions import JSONObject # noqa: PLC0415@@ -5814,7 +5839,15 @@ def get_task_summaries(team_id: int, user_id: int | None, *, ids: list) -> list[default=Value("background"),output_field=CharField(),),- _data=JSONObject(id="id", status="status", environment="environment", mode="_mode"),+ _data=JSONObject(+ id="id",+ status="status",+ environment="environment",+ mode="_mode",+ pr_url=KeyTransform("pr_url", "output"),+ pr_state=KeyTransform("pr_state", "output"),+ pr_merged=KeyTransform("pr_merged", "output"),+ ),))tasks = (@@ -5823,32 +5856,19 @@ def get_task_summaries(team_id: int, user_id: int | None, *, ids: list) -> list[.annotate(_latest_run=Subquery(latest_run.values("_data")[:1])).order_by("-created_at", "id"))- summaries: list[contracts.TaskSummaryDTO] = []- for task in tasks:- raw = getattr(task, "_latest_run", None)- latest = (- contracts.TaskLatestRunSummaryDTO(- id=raw["id"],- status=raw.get("status"),- environment=raw.get("environment"),- mode=raw.get("mode", "background"),- )- if isinstance(raw, dict)- else None- )- summaries.append(- contracts.TaskSummaryDTO(- id=task.id,- title=task.title,- repository=task.repository,- created_by_id=task.created_by_id,- created_at=task.created_at,- updated_at=task.updated_at,- origin_product=task.origin_product,- latest_run=latest,- )+ return [+ contracts.TaskSummaryDTO(+ id=task.id,+ title=task.title,+ repository=task.repository,+ created_by_id=task.created_by_id,+ created_at=task.created_at,+ updated_at=task.updated_at,+ origin_product=task.origin_product,+ latest_run=_latest_run_summary(getattr(task, "_latest_run", None)),)- return summaries+ for task in tasks+ ]def compute_repository_readiness(team_id: int, *, repository: str, window_days: int, refresh: bool) -> dict:diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex e933feaa20d0..921213010cf3 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -382,6 +382,8 @@ class TaskLatestRunSummaryDTO:status: str | Noneenvironment: str | Nonemode: Literal["interactive", "background"]+ pr_url: str | None = None+ pr_state: str | None = None@dataclass(frozen=True)@@ -389,7 +391,7 @@ class TaskSummaryDTO:"""The HTTP summary representation of a task.Mirrors exactly the fields ``TaskSummarySerializer`` emits. ``latest_run`` carries the- most-recent run's status, environment, and mode (or ``None`` when the task has no runs).+ most-recent run's status, environment, mode and pull request (or ``None`` when the task has no runs)."""id: UUIDdiff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 936d1e7a1fbb..86ac961278ba 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -2009,6 +2009,18 @@ class TaskRunSummarySerializer(serializers.Serializer):choices=TaskExecutionMode.choices,help_text="Execution mode of the latest run.",)+ pr_url = serializers.CharField(+ allow_null=True,+ help_text="URL of the pull request the latest run opened, or null when it opened none.",+ )+ pr_state = serializers.ChoiceField(+ choices=[*tasks_facade.PR_STATES, "unknown"],+ allow_null=True,+ help_text=(+ "State of that pull request: open, draft, merged, closed, or unknown. "+ "Null when the latest run opened no pull request."+ ),+ )class TaskSummarySerializer(DataclassSerializer):diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex c62466367047..2c2e9e38b2b6 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -5162,6 +5162,10 @@ class TestTaskInternalFilterAPI(BaseTaskAPITest):self.assertFalse(response.json()["internal"])+_PR_URL = "https://github.com/posthog/posthog-js/pull/1"+_OTHER_PR_URL = "https://github.com/posthog/posthog-js/pull/2"++class TestTaskSummariesAPI(BaseTaskAPITest):SUMMARIES_URL = "/api/projects/@current/tasks/summaries/"SUMMARY_FIELDS = {@@ -5238,6 +5242,8 @@ class TestTaskSummariesAPI(BaseTaskAPITest):"status": valid_run.status,"environment": valid_run.environment,"mode": "background",+ "pr_url": None,+ "pr_state": None,},)@@ -5274,12 +5280,81 @@ class TestTaskSummariesAPI(BaseTaskAPITest):"status": run.status,"environment": run.environment,"mode": expected_mode,+ "pr_url": None,+ "pr_state": None,}if runelse None)self.assertEqual(payload["latest_run"], expected_run)+ @parameterized.expand(+ [+ ("no_pr", {}, None, None),+ ("null_output", None, None, None),+ ("invalid_pr_url", {"pr_url": {"unexpected": "value"}}, None, None),+ ("pr_without_state", {"pr_url": _PR_URL}, _PR_URL, "unknown"),+ ("invalid_pr_state", {"pr_url": _PR_URL, "pr_state": "unexpected"}, _PR_URL, "unknown"),+ ("open_pr", {"pr_url": _PR_URL, "pr_state": "open"}, _PR_URL, "open"),+ ("merged_by_state", {"pr_url": _PR_URL, "pr_state": "merged"}, _PR_URL, "merged"),+ ("merged_by_webhook_flag", {"pr_url": _PR_URL, "pr_state": "open", "pr_merged": True}, _PR_URL, "merged"),+ ]+ )+ def test_summaries_latest_run_pull_request(self, _name, output, expected_pr_url, expected_pr_state):+ task = self.create_task("Task")+ TaskRun.objects.create(+ team=self.team,+ task=task,+ status=TaskRun.Status.COMPLETED,+ environment=TaskRun.Environment.CLOUD,+ output=output,+ )++ response = self.post_summaries([str(task.id)])++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ [payload] = response.json()["results"]+ self.assertEqual(payload["latest_run"]["pr_url"], expected_pr_url)+ self.assertEqual(payload["latest_run"]["pr_state"], expected_pr_state)++ def test_summaries_refresh_latest_pr_in_one_query(self):+ tasks = [self.create_task(f"Task {index}") for index in range(3)]+ task_updated_at = tasks[0].updated_at+ for task in tasks:+ TaskRun.objects.create(+ team=self.team,+ task=task,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": _PR_URL, "pr_state": "open"},+ )+ latest_pr_url = "https://github.com/example/project/pull/2"+ latest_run = TaskRun.objects.create(+ team=self.team,+ task=tasks[0],+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": latest_pr_url, "pr_state": "open", "pr_merged": False},+ )+ for pr_state, pr_merged, expected_state in [+ ("open", False, "open"),+ ("closed", False, "closed"),+ ("open", True, "merged"),+ ]:+ with self.subTest(pr_state=pr_state, pr_merged=pr_merged):+ TaskRun.update_output_atomic(latest_run.id, updates={"pr_state": pr_state, "pr_merged": pr_merged})+ with self.assertNumQueries(1):+ summaries = tasks_facade.get_task_summaries(+ self.team.id, self.user.id, ids=[task.id for task in tasks]+ )+ self.assertEqual(len(summaries), len(tasks))+ summary = next(summary for summary in summaries if summary.id == tasks[0].id)+ assert summary.latest_run is not None+ self.assertEqual(str(summary.latest_run.id), str(latest_run.id))+ self.assertEqual(summary.latest_run.pr_url, latest_pr_url)+ self.assertEqual(summary.latest_run.pr_state, expected_state)+ tasks[0].refresh_from_db()+ self.assertEqual(tasks[0].updated_at, task_updated_at)+ self.assertEqual(summary.updated_at, task_updated_at)+def test_summaries_paginates_large_id_sets(self):tasks = [self.create_task(f"Task {i}") for i in range(3)]ids = [str(t.id) for t in tasks]@@ -5315,10 +5390,6 @@ class TestTaskSummariesAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-_PR_URL = "https://github.com/posthog/posthog-js/pull/1"-_OTHER_PR_URL = "https://github.com/posthog/posthog-js/pull/2"--class TestTaskRunAPI(BaseTaskAPITest):def _create_run_for_origin(self, origin_product: Task.OriginProduct) -> tuple[Task, TaskRun]:task = Task.objects.create(diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 083472dd753c..35bd005104b2 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -4750,6 +4750,23 @@ export const TaskRunEnvironmentEnumApi = {Cloud: 'cloud',} as const+/**+ * * `open` - open+ * * `draft` - draft+ * * `merged` - merged+ * * `closed` - closed+ * * `unknown` - unknown+ */+export type PrStateEnumApi = (typeof PrStateEnumApi)[keyof typeof PrStateEnumApi]++export const PrStateEnumApi = {+ Open: 'open',+ Draft: 'draft',+ Merged: 'merged',+ Closed: 'closed',+ Unknown: 'unknown',+} as const+export interface TaskRunSummaryApi {/** ID of the latest run. */id: string@@ -4760,6 +4777,19 @@ export interface TaskRunSummaryApi {* * `interactive` - interactive* * `background` - background */mode: TaskExecutionModeEnumApi+ /**+ * URL of the pull request the latest run opened, or null when it opened none.+ * @nullable+ */+ pr_url: string | null+ /** State of that pull request: open, draft, merged, closed, or unknown. Null when the latest run opened no pull request.+ *+ * * `open` - open+ * * `draft` - draft+ * * `merged` - merged+ * * `closed` - closed+ * * `unknown` - unknown */+ pr_state: PrStateEnumApi | null}export interface TaskSearchResultApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3fa7a8b03a64..2b3e17085f0f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -62019,6 +62019,24 @@ export namespace Schemas {Cloud: 'cloud',} as const;+ /**+ * * `open` - open+ * * `draft` - draft+ * * `merged` - merged+ * * `closed` - closed+ * * `unknown` - unknown+ */+ export type PrStateEnum = typeof PrStateEnum[keyof typeof PrStateEnum];+++ export const PrStateEnum = {+ Open: 'open',+ Draft: 'draft',+ Merged: 'merged',+ Closed: 'closed',+ Unknown: 'unknown',+ } as const;+export interface TaskRunSummary {/** ID of the latest run. */id: string;@@ -62029,6 +62047,19 @@ export namespace Schemas {* * `interactive` - interactive* * `background` - background */mode: TaskExecutionModeEnum;+ /**+ * URL of the pull request the latest run opened, or null when it opened none.+ * @nullable+ */+ pr_url: string | null;+ /** State of that pull request: open, draft, merged, closed, or unknown. Null when the latest run opened no pull request.+ *+ * * `open` - open+ * * `draft` - draft+ * * `merged` - merged+ * * `closed` - closed+ * * `unknown` - unknown */+ pr_state: PrStateEnum | null;}/**