Skip to content

: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.

fix(tasks): keep a task's PR on latest_run across a resume (#101312)

Phil Haack270c6521dc1e
diff --git a/docs/internal/task-summaries.md b/docs/internal/task-summaries.md
index 8a920c27504d..5a4546279bab 100644
--- a/docs/internal/task-summaries.md
+++ b/docs/internal/task-summaries.md
@@ -6,15 +6,24 @@ 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_url`: the task's PR URL, or null when the task has no recorded PR.
- `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.
+These fields describe the PR the task points at, which is not always one the latest run opened.
+A run that opens no PR of its own starts with an empty output, which is what a resume or a
+follow-up message produces. These fields then report the most recent run that did open a PR. A run
+that opened its own PR reports that one. This matches the `latest_run` the task detail endpoint
+returns, so both endpoints answer the same way about the same task.
+
+A URL counts only when it is a non-empty string, recorded under either `pr_url` or `pr_urls`. For a
+run that recorded only `pr_urls`, `pr_url` reports the first usable entry.
+
+The batch query selects these fields with the run status, in one subquery for the latest run and one
+for the latest run holding a PR. 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.
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index ca9fb0af30ab..036ae6de3429 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -5,7 +5,7 @@ import logging
from collections import Counter
from collections.abc import Collection, Iterable, Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from datetime import datetime, timedelta
from typing import Any, Literal
from urllib.parse import urlparse
@@ -19,6 +19,7 @@ from django.core.exceptions import (
)
from django.db import IntegrityError, transaction
from django.db.models import (
+ BooleanField,
Case,
CharField,
Count,
@@ -310,6 +311,7 @@ __all__ = [
"task_exists",
"task_ids_with_pr_url_subquery",
"get_pull_requests_for_tasks",
+ "get_prior_pr_output_by_task",
"read_pr_urls",
"task_run_has_slack_mapping",
"task_run_is_terminal",
@@ -579,6 +581,49 @@ class _LatestRunUnset:
_LATEST_RUN_UNSET = _LatestRunUnset()
+class _PriorPrOutputUnset:
+ pass
+
+
+_PRIOR_PR_OUTPUT_UNSET = _PriorPrOutputUnset()
+
+# The fields that identify the PR a task points at. A run that opened no PR of its own
+# borrows these from the run that did; everything else in an output stays run-local.
+_INHERITED_PR_OUTPUT_KEYS = ("pr_url", "pr_urls", "pr_summaries", "pr_state", "pr_merged")
+
+
+def _inherited_pr_fields(output: object) -> dict[str, Any]:
+ if not isinstance(output, dict):
+ return {}
+ urls = read_pr_urls(output)
+ if not urls:
+ return {}
+ fields = {key: output[key] for key in _INHERITED_PR_OUTPUT_KEYS if key in output}
+ # An output can carry `pr_urls` without `pr_url`, and some readers look only at the latter
+ # (the feed's `has_pr` predicate, `get_latest_pr_url_by_task`), so mirror the primary-first
+ # shape `merge_pr_output` stores.
+ primary = output.get("pr_url")
+ if not isinstance(primary, str) or not primary:
+ primary = urls[0]
+ fields["pr_url"] = primary
+ fields["pr_urls"] = [primary, *(url for url in urls if url != primary)]
+ return fields
+
+
+def _prior_pr_output_from_runs(task: Task) -> dict[str, Any] | None:
+ """The task's most recent PR-carrying run output, taken from the runs already in memory.
+
+ Every caller that maps one task prefetches ``runs``, and ``Task.latest_run`` has just walked
+ them, so the row this needs is loaded — a query for it would be a second trip for rows the
+ request already holds. Same team scoping and same recency rule as ``Task.latest_run``. The
+ list path batches its own lookup instead and passes the result in.
+ """
+ pr_runs = [run for run in task.runs.all() if run.team_id == task.team_id and read_pr_urls(run.output)]
+ if not pr_runs:
+ return None
+ return max(pr_runs, key=lambda run: (run.created_at, run.id)).output
+
+
def _task_slack_thread_references(task: Task) -> list[contracts.SlackThreadReferenceDTO]:
references: list[contracts.SlackThreadReferenceDTO] = []
for item in (task.state or {}).get("slack_thread_references", []):
@@ -673,8 +718,15 @@ def _task_detail_to_dto(
include_latest_run: bool = True,
latest_run: TaskRun | None | _LatestRunUnset = _LATEST_RUN_UNSET,
include_latest_run_log_url: bool = True,
+ prior_pr_output: dict[str, Any] | None | _PriorPrOutputUnset = _PRIOR_PR_OUTPUT_UNSET,
) -> contracts.TaskDetailDTO:
- """Map a ``Task`` to its HTTP detail DTO."""
+ """Map a ``Task`` to its HTTP detail DTO.
+
+ ``prior_pr_output`` is the task's most recent PR-carrying run output, which backfills
+ the PR onto ``latest_run`` when that run opened none itself. Callers that map a page of
+ tasks pass it to keep the lookup to one query; a single task leaves it unset and the
+ answer comes from the runs that caller already prefetched.
+ """
if not include_latest_run:
resolved_latest_run = None
elif isinstance(latest_run, _LatestRunUnset):
@@ -684,6 +736,23 @@ def _task_detail_to_dto(
latest_run_id = getattr(task, "_latest_run_id", None)
if latest_run_id is None and resolved_latest_run is not None:
latest_run_id = resolved_latest_run.id
+ latest_run_dto = (
+ _task_run_detail_to_dto(
+ resolved_latest_run, task=task, user_id=user_id, include_log_url=include_latest_run_log_url
+ )
+ if resolved_latest_run is not None
+ else None
+ )
+ if latest_run_dto is not None and not read_pr_urls(latest_run_dto.output):
+ # A resumed run starts with an empty output, so the PR an earlier run opened drops
+ # out of `latest_run` — and with it the PR button every client reads from there.
+ # Logs and artifacts already survive a resume; the PR has to as well.
+ resolved_prior_pr_output = (
+ _prior_pr_output_from_runs(task) if isinstance(prior_pr_output, _PriorPrOutputUnset) else prior_pr_output
+ )
+ inherited = _inherited_pr_fields(resolved_prior_pr_output)
+ if inherited:
+ latest_run_dto = replace(latest_run_dto, output={**(latest_run_dto.output or {}), **inherited})
return contracts.TaskDetailDTO(
id=task.id,
task_number=task.task_number,
@@ -703,13 +772,7 @@ def _task_detail_to_dto(
archived=task.archived,
archived_at=task.archived_at,
ci_prompt=task.ci_prompt,
- latest_run=(
- _task_run_detail_to_dto(
- resolved_latest_run, task=task, user_id=user_id, include_log_url=include_latest_run_log_url
- )
- if resolved_latest_run is not None
- else None
- ),
+ latest_run=latest_run_dto,
created_at=task.created_at,
updated_at=task.updated_at,
last_activity_at=task.last_activity_at or task.updated_at,
@@ -1082,29 +1145,67 @@ def get_pull_requests_for_tasks(
return result
+def _jsonb_path_exists(path: str) -> Func:
+ """``jsonb_path_exists(output, <literal path>)``. The path is always a literal here, so no
+ caller input reaches the expression."""
+ return Func("output", Value(path), function="jsonb_path_exists", output_field=BooleanField())
+
+
+# A run carries a PR when its output yields a usable URL — the rule ``read_pr_urls`` applies in
+# Python: a non-empty *string* under ``pr_url``, or any non-empty string in ``pr_urls``. Both
+# halves check the JSON type, so SQL selects a run exactly when Python can read a URL out of it.
+# Without that, `{"pr_url": 123}` satisfies a bare non-empty test and wins the newest-run pick,
+# then Python finds no URL and an older run holding the real PR is never reached. Indexing
+# ``pr_urls[0]`` would be wrong for the same reason: it misses ``["", "…/pull/1"]``.
+_PR_CARRYING_OUTPUT_Q = Q(_jsonb_path_exists('$.pr_url ? (@.type() == "string" && @ != "")')) | Q(
+ _jsonb_path_exists('$.pr_urls[*] ? (@.type() == "string" && @ != "")')
+)
+
+
def get_latest_pr_url_by_task(task_ids: Iterable[str | UUID], *conditions: Q) -> dict[str, str]:
- """Latest non-empty ``output.pr_url`` per task, for the supplied task ids."""
+ """Latest usable PR URL per task, for the supplied task ids.
+
+ Reads the same normalized shape as everything else: the newest run that carries a PR, and its
+ primary URL whether the run recorded ``pr_url`` or only ``pr_urls``. Matching ``pr_url`` alone
+ left a ``pr_urls``-only run with no URL here, which is how Slack App Home lost the link.
+ """
ids = [str(t) for t in task_ids]
if not ids:
return {}
rows = (
- TaskRun.objects.filter(*conditions, task_id__in=ids, output__pr_url__isnull=False)
- .exclude(output__pr_url="")
+ TaskRun.objects.filter(*conditions, task_id__in=ids)
+ .filter(_PR_CARRYING_OUTPUT_Q)
+ .order_by("task_id", "-created_at", "-id")
+ .distinct("task_id")
+ .values_list("task_id", "output")
+ )
+ urls_by_task = ((str(task_id), read_pr_urls(output)) for task_id, output in rows)
+ return {task_id: urls[0] for task_id, urls in urls_by_task if urls}
+
+
+def get_prior_pr_output_by_task(team_id: int, task_ids: Iterable[str | UUID]) -> dict[str, dict[str, Any]]:
+ """Most recent run ``output`` that carries a PR, per task.
+
+ A run records the PR it opened in its own ``output``. A later run — a resume, a follow-up
+ message — starts with an empty ``output``, so a reader that sees only the newest run finds
+ no PR on a task that plainly has one. This supplies the PR that run inherits.
+ """
+ ids = [str(task_id) for task_id in task_ids]
+ if not ids:
+ return {}
+ rows = (
+ TaskRun.objects.filter(team_id=team_id, task_id__in=ids)
+ .filter(_PR_CARRYING_OUTPUT_Q)
.order_by("task_id", "-created_at", "-id")
- .annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
- .values("task_id", "output_pr_url_text")
.distinct("task_id")
+ .values_list("task_id", "output")
)
- return {str(row["task_id"]): row["output_pr_url_text"] for row in rows if row["output_pr_url_text"]}
+ return {str(task_id): output for task_id, output in rows if isinstance(output, dict)}
def task_ids_with_pr_url_subquery(team_id: int, *conditions: Q) -> QuerySet[TaskRun, Any]:
"""Find same-team tasks with a primary PR or a PR array, including array-only outputs."""
- return (
- TaskRun.objects.filter(*conditions, team_id=team_id)
- .filter((Q(output__pr_url__isnull=False) & ~Q(output__pr_url="")) | Q(output__pr_urls__0__isnull=False))
- .values("task_id")
- )
+ return TaskRun.objects.filter(*conditions, team_id=team_id).filter(_PR_CARRYING_OUTPUT_Q).values("task_id")
def latest_task_run_pr_url_subquery(*conditions: Q, **task_run_filter) -> Subquery:
@@ -5700,19 +5801,23 @@ def _list_tasks_queryset(
qs = qs.annotate(_latest_run_status=Subquery(latest_run_status)).filter(_latest_run_status=status_filter)
# PR/CI state filters read the snapshot the PR webhook and the CI follow-up
- # loop persist onto the latest run's output (same latest-run subquery shape
- # as the status filter, so "the task's PR" means what the API's latest_run
- # shows). KeyTextTransform, so the comparison is text = text.
+ # loop persist onto a run's output. KeyTextTransform, so the comparison is
+ # text = text.
pr_state = filters.get("pr_state")
if pr_state:
- latest_run_pr_state = latest_run.annotate(_pr_state=KeyTextTransform("pr_state", "output")).values("_pr_state")[
- :1
- ]
+ # Anchored on the newest PR-carrying run, the one `_task_detail_to_dto` inherits
+ # `latest_run.output` from. A resumed run never gains a `pr_state` of its own, so reading
+ # the newest run would answer `pr_state=open` differently from the `latest_run` this same
+ # endpoint returns.
+ latest_pr_run = latest_run.filter(_PR_CARRYING_OUTPUT_Q)
+ latest_run_pr_state = latest_pr_run.annotate(_pr_state=KeyTextTransform("pr_state", "output")).values(
+ "_pr_state"
+ )[:1]
qs = qs.annotate(_latest_run_pr_state=Subquery(latest_run_pr_state))
if pr_state == "merged":
# Runs merged before pr_state existed only carry the older
# pr_merged flag; honor both spellings.
- latest_run_pr_merged = latest_run.annotate(_pr_merged=KeyTextTransform("pr_merged", "output")).values(
+ latest_run_pr_merged = latest_pr_run.annotate(_pr_merged=KeyTextTransform("pr_merged", "output")).values(
"_pr_merged"
)[:1]
qs = qs.annotate(_latest_run_pr_merged=Subquery(latest_run_pr_merged)).filter(
@@ -5721,6 +5826,8 @@ def _list_tasks_queryset(
else:
qs = qs.filter(_latest_run_pr_state=pr_state)
+ # `ci_status` stays on the newest run: unlike the PR, it is not inherited across a resume.
+
ci_status = filters.get("ci_status")
if ci_status:
latest_run_ci_status = latest_run.annotate(_ci_status=KeyTextTransform("ci_status", "output")).values(
@@ -5808,8 +5915,21 @@ def _latest_runs_by_task_id(task_ids: Iterable[UUID], team_id: int) -> dict[UUID
def _tasks_to_dtos(tasks: Iterable[Task], team_id: int, user_id: int | None = None) -> list[contracts.TaskDetailDTO]:
task_list = list(tasks)
latest_runs_by_task_id = _latest_runs_by_task_id((task.id for task in task_list), team_id)
+ # Resolved for the whole page in one query, rather than one per task inside the mapper.
+ needs_prior_pr = [
+ task.id
+ for task in task_list
+ if (run := latest_runs_by_task_id.get(task.id)) is not None and not read_pr_urls(run.output)
+ ]
+ prior_pr_output_by_task_id = get_prior_pr_output_by_task(team_id, needs_prior_pr)
return [
- _task_detail_to_dto(task, user_id=user_id, latest_run=latest_runs_by_task_id.get(task.id)) for task in task_list
+ _task_detail_to_dto(
+ task,
+ user_id=user_id,
+ latest_run=latest_runs_by_task_id.get(task.id),
+ prior_pr_output=prior_pr_output_by_task_id.get(str(task.id)),
+ )
+ for task in task_list
]
@@ -5963,18 +6083,23 @@ 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, *, can_read_summary: bool) -> contracts.TaskLatestRunSummaryDTO | None:
+def _latest_run_summary(
+ raw: object, prior_pr: object = None, *, can_read_summary: bool
+) -> 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
+ # Same inheritance the task detail response applies: a run that opened no PR of its own shows
+ # the one an earlier run opened, so the sidebar and the detail view agree about a resumed task.
+ pr_source = raw if read_pr_urls(raw) else (prior_pr if isinstance(prior_pr, dict) else {})
+ urls = read_pr_urls(pr_source)
+ pr_url = urls[0] if urls 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,
+ pr_state=_pull_request_state(pr_source) if pr_url else None,
task_summary=(raw.get("task_summary") or raw.get("prior_run_summary")) if can_read_summary else None,
)
@@ -6000,6 +6125,7 @@ def get_task_summaries(
environment="environment",
mode="_mode",
pr_url=KeyTransform("pr_url", "output"),
+ pr_urls=KeyTransform("pr_urls", "output"),
pr_state=KeyTransform("pr_state", "output"),
pr_merged=KeyTransform("pr_merged", "output"),
task_summary="state__task_summary",
@@ -6007,10 +6133,27 @@ def get_task_summaries(
),
)
)
+ # The newest run that opened a PR, which is not always the newest run.
+ latest_pr_run = (
+ TaskRun.objects.filter(task=OuterRef("pk"), team_id=team_id)
+ .filter(_PR_CARRYING_OUTPUT_Q)
+ .order_by("-created_at", "-id")
+ .annotate(
+ _pr=JSONObject(
+ pr_url=KeyTransform("pr_url", "output"),
+ pr_urls=KeyTransform("pr_urls", "output"),
+ pr_state=KeyTransform("pr_state", "output"),
+ pr_merged=KeyTransform("pr_merged", "output"),
+ )
+ )
+ )
tasks = (
Task.objects.filter(team_id=team_id, deleted=False, id__in=ids)
.filter(task_visibility_q(user_id))
- .annotate(_latest_run=Subquery(latest_run.values("_data")[:1]))
+ .annotate(
+ _latest_run=Subquery(latest_run.values("_data")[:1]),
+ _latest_pr_run=Subquery(latest_pr_run.values("_pr")[:1]),
+ )
.order_by("-created_at", "id")
)
count = tasks.count()
@@ -6020,7 +6163,7 @@ def get_task_summaries(
for task in tasks:
raw = getattr(task, "_latest_run", None)
can_read_summary = task.origin_product != Task.OriginProduct.WORKFLOW or task.created_by_id == user_id
- latest = _latest_run_summary(raw, can_read_summary=can_read_summary)
+ latest = _latest_run_summary(raw, getattr(task, "_latest_pr_run", None), can_read_summary=can_read_summary)
summaries.append(
contracts.TaskSummaryDTO(
id=task.id,
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index db263d4d0a1f..90ebf197438c 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -5,7 +5,7 @@ import base64
import asyncio
import hashlib
from collections.abc import AsyncGenerator, Iterator
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
from decimal import Decimal
from typing import Any, ClassVar, cast
from urllib.parse import quote
@@ -5392,8 +5392,13 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual({t["id"] for t in response.json()["results"]}, {str(mentioned.id)})
- def test_filter_by_pr_state_uses_latest_run_not_any_run(self):
- """A task whose latest run has no PR state must not match an older run's state."""
+ def test_filter_by_pr_state_uses_the_latest_run_that_opened_a_pr(self):
+ """A resume doesn't drop the task's PR, so the filter reads the run that opened it.
+
+ The task response inherits that PR onto `latest_run.output` (see `_inherited_pr_fields`),
+ so anchoring this filter on the newest run instead would make `?pr_state=open` disagree
+ with the `latest_run` the same endpoint returns for the same task.
+ """
base_time = django_timezone.now()
task = self.create_task("Task with mixed PR runs")
@@ -5410,10 +5415,35 @@ class TestTaskAPI(BaseTaskAPITest):
status=TaskRun.Status.IN_PROGRESS,
created_at=base_time + timedelta(seconds=1),
)
+ self.create_task("Task that never opened a PR")
response = self.client.get("/api/projects/@current/tasks/?pr_state=open")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["results"], [])
+ self.assertEqual([t["id"] for t in response.json()["results"]], [str(task.id)])
+
+ def test_filter_by_pr_state_prefers_the_newer_of_two_prs(self):
+ """Two runs with their own PRs: the newer one's state is the task's."""
+ base_time = datetime(2026, 1, 1, tzinfo=UTC)
+
+ task = self.create_task("Task with two PRs")
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ created_at=base_time,
+ output={"pr_url": "https://github.com/posthog/posthog/pull/1", "pr_state": "open"},
+ )
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ created_at=base_time + timedelta(seconds=1),
+ output={"pr_url": "https://github.com/posthog/posthog/pull/2", "pr_state": "closed"},
+ )
+
+ self.assertEqual(self.client.get("/api/projects/@current/tasks/?pr_state=open").json()["results"], [])
+ closed = self.client.get("/api/projects/@current/tasks/?pr_state=closed")
+ self.assertEqual([t["id"] for t in closed.json()["results"]], [str(task.id)])
def test_filter_by_status_uses_latest_run_not_any_run(self):
"""A task whose latest run is in_progress must not match status=completed, even if an older run completed."""
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 36c8c6665184..6d5e5a1032a9 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -572,6 +572,304 @@ class TestFacadeReadsAndMappers(TestCase):
self.assertEqual(facade.get_latest_pr_url_by_task([]), {})
+ def test_get_prior_pr_output_by_task_picks_the_newest_pr_carrying_run(self):
+ task = self._make_task()
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/1"}
+ )
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_urls": ["https://x/pull/2"]}
+ )
+ # A resume opens no PR of its own, so it must not hide the run that did.
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+ no_pr_task = self._make_task()
+ TaskRun.objects.create(task=no_pr_task, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ prior = facade.get_prior_pr_output_by_task(self.team.id, [task.id, no_pr_task.id])
+
+ self.assertEqual(prior, {str(task.id): {"pr_urls": ["https://x/pull/2"]}})
+ self.assertEqual(facade.get_prior_pr_output_by_task(self.team.id, []), {})
+
+ def test_task_detail_keeps_the_pr_on_latest_run_across_a_resume(self):
+ task = self._make_task()
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={
+ "pr_url": "https://x/pull/7",
+ "pr_urls": ["https://x/pull/7"],
+ "pr_state": "open",
+ "commit_push": {"repository": "posthog/posthog"},
+ },
+ )
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"final_message": "done"}
+ )
+
+ # The runs this path prefetches already carry the earlier PR, so finding it costs
+ # no second trip to the database.
+ with self.assertNumQueries(3):
+ dto = facade.get_task_detail(task.id, self.team.id, self.user.id)
+
+ assert dto is not None and dto.latest_run is not None and dto.latest_run.output is not None
+ output = dto.latest_run.output
+ self.assertEqual(output["pr_url"], "https://x/pull/7")
+ self.assertEqual(output["pr_urls"], ["https://x/pull/7"])
+ self.assertEqual(output["pr_state"], "open")
+ self.assertEqual(output["final_message"], "done")
+ # Only the PR travels; the rest of an earlier run's output stays where it was written.
+ self.assertNotIn("commit_push", output)
+
+ def test_task_detail_leaves_a_run_that_opened_its_own_pr_alone(self):
+ task = self._make_task()
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/1"}
+ )
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/2"}
+ )
+
+ dto = facade.get_task_detail(task.id, self.team.id, self.user.id)
+
+ assert dto is not None and dto.latest_run is not None and dto.latest_run.output is not None
+ self.assertEqual(dto.latest_run.output["pr_url"], "https://x/pull/2")
+
+ def test_get_prior_pr_output_by_task_skips_an_empty_pr_urls_entry(self):
+ task = self._make_task()
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/1"}
+ )
+ # Storable, carries no PR, and so must not shadow the older run that has one.
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_urls": [""]})
+
+ prior = facade.get_prior_pr_output_by_task(self.team.id, [task.id])
+
+ self.assertEqual(prior, {str(task.id): {"pr_url": "https://x/pull/1"}})
+
+ def test_get_prior_pr_output_by_task_matches_a_later_non_empty_pr_url(self):
+ task = self._make_task()
+ # `read_pr_urls` drops the empty entry and still yields a usable URL, so the SQL
+ # predicate has to agree with it rather than looking only at the first entry.
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_urls": ["", "https://x/pull/2"]},
+ )
+
+ prior = facade.get_prior_pr_output_by_task(self.team.id, [task.id])
+
+ self.assertEqual(prior, {str(task.id): {"pr_urls": ["", "https://x/pull/2"]}})
+
+ def test_list_tasks_pr_state_filter_matches_a_later_non_empty_pr_url(self):
+ task = self._make_task(title="empty first entry")
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_urls": ["", "https://x/pull/2"], "pr_state": "open"},
+ )
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ open_ids = [dto.id for dto in facade.list_tasks(self.team.id, self.user.id, filters={"pr_state": "open"})]
+
+ self.assertEqual(open_ids, [task.id])
+
+ def test_task_detail_fills_pr_url_from_an_array_only_prior_output(self):
+ task = self._make_task()
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_urls": ["https://x/pull/9"]}
+ )
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ dto = facade.get_task_detail(task.id, self.team.id, self.user.id)
+
+ # Readers that look only at `pr_url` (the feed's `has_pr`, `get_latest_pr_url_by_task`)
+ # have to see the PR too.
+ assert dto is not None and dto.latest_run is not None and dto.latest_run.output is not None
+ self.assertEqual(dto.latest_run.output["pr_url"], "https://x/pull/9")
+ self.assertEqual(dto.latest_run.output["pr_urls"], ["https://x/pull/9"])
+
+ def test_list_tasks_pr_state_filter_matches_an_inherited_pr(self):
+ resumed = self._make_task(title="resumed open pr")
+ TaskRun.objects.create(
+ task=resumed,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": "https://x/pull/1", "pr_state": "open"},
+ )
+ TaskRun.objects.create(task=resumed, team=self.team, status=TaskRun.Status.COMPLETED)
+ merged = self._make_task(title="resumed merged pr")
+ TaskRun.objects.create(
+ task=merged,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ # Legacy merge: the pr_merged flag, no pr_state.
+ output={"pr_url": "https://x/pull/2", "pr_merged": True},
+ )
+ TaskRun.objects.create(task=merged, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ # The filter and `latest_run.output` have to answer the same way about the same task.
+ open_ids = [dto.id for dto in facade.list_tasks(self.team.id, self.user.id, filters={"pr_state": "open"})]
+ merged_ids = [dto.id for dto in facade.list_tasks(self.team.id, self.user.id, filters={"pr_state": "merged"})]
+
+ self.assertEqual(open_ids, [resumed.id])
+ self.assertEqual(merged_ids, [merged.id])
+
+ @patch("products.tasks.backend.facade.api._task_run_log_url", return_value="https://presigned/log")
+ def test_task_detail_inherits_a_pr_without_restoring_a_suppressed_log_url(self, _mock_log_url):
+ """The degraded `start_task_run` fallback omits the log URL, and inheriting a PR must keep it out.
+
+ The backfill rebuilds the run DTO, so the caller's gate has to be applied where that DTO is
+ built rather than at the `latest_run` keyword, or the fallback silently regains the
+ presigned-URL I/O it exists to avoid.
+ """
+ task = self._make_task()
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/4"}
+ )
+ latest = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ suppressed = facade._task_detail_to_dto(task, latest_run=latest, include_latest_run_log_url=False)
+ allowed = facade._task_detail_to_dto(task, latest_run=latest)
+
+ assert suppressed.latest_run is not None and suppressed.latest_run.output is not None
+ self.assertIsNone(suppressed.latest_run.log_url)
+ self.assertEqual(suppressed.latest_run.output["pr_url"], "https://x/pull/4")
+ # The open-gate call proves the assertion above isn't passing for want of a URL to begin with.
+ assert allowed.latest_run is not None
+ self.assertEqual(allowed.latest_run.log_url, "https://presigned/log")
+
+ def test_get_prior_pr_output_by_task_skips_a_non_string_pr_url(self):
+ task = self._make_task()
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/real"}
+ )
+ # `output` is free-form JSON, and `read_pr_urls` reads only strings. A newest run whose
+ # `pr_url` is a number must not win the pick and strand the older run that holds the PR.
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": 123})
+
+ prior = facade.get_prior_pr_output_by_task(self.team.id, [task.id])
+
+ self.assertEqual(prior, {str(task.id): {"pr_url": "https://x/pull/real"}})
+
+ def test_list_tasks_never_reports_a_non_string_pr_url(self):
+ task = self._make_task(title="junk pr_url")
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/real"}
+ )
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": True})
+
+ listed = next(dto for dto in facade.list_tasks(self.team.id, self.user.id, filters={}) if dto.id == task.id)
+
+ # The list and the detail response have to agree, and neither may hand a client a
+ # non-string where a URL belongs.
+ assert listed.latest_run is not None and listed.latest_run.output is not None
+ self.assertEqual(listed.latest_run.output["pr_url"], "https://x/pull/real")
+
+ def test_get_latest_pr_url_by_task_reads_an_array_only_output(self):
+ array_only = self._make_task(title="array only")
+ TaskRun.objects.create(
+ task=array_only,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_urls": ["https://x/pull/7"]},
+ )
+ junk = self._make_task(title="junk only")
+ TaskRun.objects.create(task=junk, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": 5})
+
+ urls = facade.get_latest_pr_url_by_task([array_only.id, junk.id])
+
+ # Slack App Home reads this helper, so a run that recorded only `pr_urls` still has a link.
+ self.assertEqual(urls, {str(array_only.id): "https://x/pull/7"})
+
+ def test_task_summaries_inherit_the_pr_across_a_resume(self):
+ task = self._make_task(title="resumed")
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": "https://x/pull/9", "pr_state": "open"},
+ )
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+ own_pr = self._make_task(title="own pr")
+ TaskRun.objects.create(
+ task=own_pr,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": "https://x/pull/1", "pr_state": "closed"},
+ )
+
+ dtos, _ = facade.get_task_summaries(self.team.id, self.user.id, ids=[task.id, own_pr.id])
+ summaries = {dto.title: dto.latest_run for dto in dtos}
+
+ # The sidebar reads summaries while the task view reads the detail DTO; both have to show
+ # the same PR for the same task.
+ assert summaries["resumed"] is not None
+ self.assertEqual(summaries["resumed"].pr_url, "https://x/pull/9")
+ self.assertEqual(summaries["resumed"].pr_state, "open")
+ # A run that opened its own PR keeps it rather than inheriting an older one.
+ assert summaries["own pr"] is not None
+ self.assertEqual(summaries["own pr"].pr_url, "https://x/pull/1")
+ self.assertEqual(summaries["own pr"].pr_state, "closed")
+
+ def test_task_summaries_read_an_array_only_pr_url(self):
+ own = self._make_task(title="own array")
+ TaskRun.objects.create(
+ task=own,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_urls": ["https://x/pull/3"], "pr_state": "open"},
+ )
+ inherited = self._make_task(title="inherited array")
+ TaskRun.objects.create(
+ task=inherited, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_urls": ["https://x/pull/4"]}
+ )
+ TaskRun.objects.create(task=inherited, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ dtos, _ = facade.get_task_summaries(self.team.id, self.user.id, ids=[own.id, inherited.id])
+ summaries = {dto.title: dto.latest_run for dto in dtos}
+
+ # `pr_url` is the flat field clients read, so a run that recorded only the array still
+ # reports its first usable entry there — whether that run is the latest or an earlier one.
+ assert summaries["own array"] is not None and summaries["inherited array"] is not None
+ self.assertEqual(summaries["own array"].pr_url, "https://x/pull/3")
+ self.assertEqual(summaries["own array"].pr_state, "open")
+ self.assertEqual(summaries["inherited array"].pr_url, "https://x/pull/4")
+
+ def test_task_summaries_report_no_pr_when_the_task_never_opened_one(self):
+ task = self._make_task(title="no pr")
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ dtos, _ = facade.get_task_summaries(self.team.id, self.user.id, ids=[task.id])
+ summary = dtos[0].latest_run
+
+ assert summary is not None
+ self.assertIsNone(summary.pr_url)
+ self.assertIsNone(summary.pr_state)
+
+ def test_list_tasks_resolves_inherited_prs_in_one_query(self):
+ tasks = [self._make_task(title=f"pr-task-{i}") for i in range(4)]
+ for index, task in enumerate(tasks):
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": f"https://x/pull/{index}"},
+ )
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ # The page costs one inherited-PR query, whatever the number of tasks on it.
+ with self.assertNumQueries(6):
+ dtos = facade.list_tasks(self.team.id, self.user.id, filters={})
+
+ by_title = {dto.title: dto for dto in dtos}
+ for index, task in enumerate(tasks):
+ latest_run = by_title[task.title].latest_run
+ assert latest_run is not None and latest_run.output is not None
+ self.assertEqual(latest_run.output["pr_url"], f"https://x/pull/{index}")
+
def test_get_conversation_task_dtos_carries_latest_run_id_not_nested_run(self):
task = self._make_task(title="Conversation task")
TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)