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.

feat(tasks): discover home-tab PRs by branch, not just output.pr_url (#65168)

Peter Kirkham2afd5675f637
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 42cbfd3c594e..dede842c0e9c 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -448,7 +448,12 @@ class GitHubIntegrationBase:
# --- Authenticated API helpers ---
def _installation_authenticated_get(
- self, url: str, *, endpoint: str, timeout: int = 10
+ self,
+ url: str,
+ *,
+ endpoint: str,
+ params: dict[str, str | int] | None = None,
+ timeout: int = 10,
) -> requests.Response | None:
"""GET with installation token; refreshes on expiry or 401."""
try:
@@ -467,6 +472,7 @@ class GitHubIntegrationBase:
"Authorization": f"Bearer {access_token}",
"X-GitHub-Api-Version": "2022-11-28",
},
+ params=params,
timeout=timeout,
)
@@ -699,6 +705,33 @@ class GitHubIntegrationBase:
owner, repo, pr_number = parsed
return self.get_pull_request(f"{owner}/{repo}", pr_number)
+ def find_pull_request_urls_for_branch(self, repository: str, branch: str) -> list[str]:
+ """Return the HTML URLs of open or closed PRs whose head is ``branch`` in ``repository``.
+
+ ``repository`` is ``owner/repo`` (or a bare repo, resolved against the org). Results come
+ from the installation token's own API call, so they are inherently trusted — not
+ user-supplied like ``output.pr_url``. Best-effort: returns [] on a bad repo, non-200, or error.
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ owner = repo_path.split("/", 1)[0]
+ response = self._installation_authenticated_get(
+ f"https://api.github.com/repos/{repo_path}/pulls",
+ endpoint="/repos/{owner}/{repo}/pulls",
+ params={"head": f"{owner}:{branch}", "state": "all", "per_page": 10},
+ )
+ if response is None or response.status_code != 200:
+ return []
+ try:
+ pulls = response.json()
+ except Exception:
+ logger.warning(
+ "GitHubIntegration: find_pull_request_urls_for_branch non-JSON response", repository=repo_path
+ )
+ return []
+ if not isinstance(pulls, list):
+ return []
+ return [pr["html_url"] for pr in pulls if isinstance(pr, dict) and isinstance(pr.get("html_url"), str)]
+
_PR_SNAPSHOT_QUERY = """
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.py
index c83d6a9ffa6b..22db2ee7119f 100644
--- a/products/tasks/backend/temporal/__init__.py
+++ b/products/tasks/backend/temporal/__init__.py
@@ -1,4 +1,5 @@
from .automation import RunTaskAutomationWorkflow, run_task_automation_activity
+from .code_workstreams.activities.discover_branch_prs import discover_branch_prs
from .code_workstreams.activities.list_active_teams import list_active_code_teams
from .code_workstreams.activities.load_pr_urls import load_team_pr_urls
from .code_workstreams.activities.poll_pull_requests import poll_team_pull_requests
@@ -82,6 +83,7 @@ ACTIVITIES = [
snapshot_cleanup_sandbox,
list_active_code_teams,
load_team_pr_urls,
+ discover_branch_prs,
poll_team_pull_requests,
rebuild_team_workstreams,
]
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py b/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py
new file mode 100644
index 000000000000..6239e912f988
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py
@@ -0,0 +1,164 @@
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Optional
+
+from django.core.exceptions import ObjectDoesNotExist
+from django.utils import timezone
+
+import requests
+from temporalio import activity
+
+from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError
+from posthog.temporal.common.utils import close_db_connections
+
+from products.tasks.backend.logic.code_workstreams.grouping import DEFAULT_BASE_BRANCHES
+from products.tasks.backend.models import TaskRun
+from products.tasks.backend.temporal.code_workstreams.activities.github_resolution import (
+ TeamIntegrationResolver,
+ resolve_github_integration,
+)
+from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import PrRef
+from products.tasks.backend.temporal.code_workstreams.constants import (
+ ACTIVITY_WINDOW,
+ MAX_BRANCH_QUERIES_PER_TEAM_PER_CYCLE,
+)
+
+
+@dataclass
+class _BranchCandidate:
+ repository: str
+ branch: str
+ github_integration_id: Optional[int]
+ github_user_integration_id: Optional[str]
+
+
+@dataclass
+class DiscoverBranchPrsInput:
+ team_id: int
+ # PR urls already found this cycle; discovery skips these.
+ known_pr_urls: list[str]
+ # Remaining capacity before hitting MAX_PRS_PER_TEAM_PER_CYCLE.
+ budget: int
+
+
+@dataclass
+class DiscoverBranchPrsOutput:
+ prs: list[PrRef]
+
+
+@close_db_connections
+def discover_branch_prs(input: DiscoverBranchPrsInput) -> DiscoverBranchPrsOutput:
+ return discover_branch_prs_for_team(
+ input.team_id,
+ set(input.known_pr_urls),
+ input.budget,
+ heartbeat=activity.heartbeat,
+ )
+
+
+def _collect_branch_candidates(team_id: int) -> list[_BranchCandidate]:
+ """Recent runs with a branch and a repository, deduped by (repo, branch), capped per cycle.
+
+ The branch analogue of load_pr_urls' output.pr_url harvest: a run's branch is durable even
+ when no pr_url was recorded. Base branches are excluded — they never head a task's own PR.
+ """
+ cutoff = timezone.now() - ACTIVITY_WINDOW
+ runs = (
+ TaskRun.objects.filter(team_id=team_id, updated_at__gte=cutoff)
+ .exclude(branch__isnull=True)
+ .exclude(branch="")
+ .exclude(branch__in=list(DEFAULT_BASE_BRANCHES))
+ .select_related("task")
+ .order_by("-updated_at")
+ )
+ resolver = TeamIntegrationResolver(team_id)
+ seen: set[tuple[str, str]] = set()
+ candidates: list[_BranchCandidate] = []
+ for run in runs.iterator():
+ task = run.task
+ repository = task.repository
+ branch = run.branch
+ if not repository or not branch:
+ continue
+ key = (repository.casefold(), branch)
+ if key in seen:
+ continue
+ seen.add(key)
+ team_int, user_int = resolver.resolve(task)
+ if team_int is None and user_int is None:
+ continue
+ candidates.append(_BranchCandidate(repository, branch, team_int, user_int))
+ if len(candidates) >= MAX_BRANCH_QUERIES_PER_TEAM_PER_CYCLE:
+ break
+ return candidates
+
+
+def discover_branch_prs_for_team(
+ team_id: int,
+ known_pr_urls: set[str],
+ budget: int,
+ *,
+ heartbeat: Callable[[int], None] | None = None,
+) -> DiscoverBranchPrsOutput:
+ if budget <= 0:
+ return DiscoverBranchPrsOutput(prs=[])
+
+ candidates = _collect_branch_candidates(team_id)
+ integrations: dict[str, GitHubIntegrationBase | None] = {}
+ found: dict[str, PrRef] = {}
+
+ for index, candidate in enumerate(candidates):
+ if heartbeat is not None:
+ heartbeat(index)
+ if len(found) >= budget:
+ break
+
+ cache_key = (
+ f"i:{candidate.github_integration_id}"
+ if candidate.github_integration_id is not None
+ else f"u:{candidate.github_user_integration_id}"
+ )
+ try:
+ if cache_key not in integrations:
+ integrations[cache_key] = resolve_github_integration(
+ candidate.github_integration_id, candidate.github_user_integration_id
+ )
+ integration = integrations[cache_key]
+ except ObjectDoesNotExist:
+ # Cache None so other candidates sharing this integration don't re-run the failing lookup.
+ activity.logger.warning("code_workstreams_discover_integration_missing", repository=candidate.repository)
+ integrations[cache_key] = None
+ continue
+ except (GitHubIntegrationError, requests.RequestException) as e:
+ # Token-refresh failure; skip this candidate rather than aborting the activity.
+ activity.logger.warning(
+ "code_workstreams_discover_integration_unavailable", repository=candidate.repository, error=str(e)
+ )
+ continue
+ if integration is None:
+ continue
+
+ try:
+ urls = integration.find_pull_request_urls_for_branch(candidate.repository, candidate.branch)
+ except Exception as e:
+ activity.logger.warning(
+ "code_workstreams_discover_branch_failed",
+ repository=candidate.repository,
+ branch=candidate.branch,
+ error=str(e),
+ )
+ continue
+
+ for url in urls:
+ if url in known_pr_urls or url in found:
+ continue
+ found[url] = PrRef(
+ pr_url=url,
+ github_integration_id=candidate.github_integration_id,
+ github_user_integration_id=candidate.github_user_integration_id,
+ )
+ if len(found) >= budget:
+ break
+
+ return DiscoverBranchPrsOutput(prs=list(found.values()))
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/github_resolution.py b/products/tasks/backend/temporal/code_workstreams/activities/github_resolution.py
new file mode 100644
index 000000000000..8a732e9dc48c
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/activities/github_resolution.py
@@ -0,0 +1,59 @@
+from typing import Optional
+
+from posthog.models import Integration
+from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.integration import GitHubIntegration
+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
+
+from products.tasks.backend.models import Task
+
+
+class TeamIntegrationResolver:
+ """Resolve the GitHub integration ids to use for a task's PR lookups.
+
+ Order: the task's own integration, else the team default, else the task creator's personal
+ integration. Shared by ``load_pr_urls`` and ``discover_branch_prs`` to keep resolution in sync.
+ """
+
+ def __init__(self, team_id: int) -> None:
+ self._team_github_id: Optional[int] = (
+ Integration.objects.filter(team_id=team_id, kind="github").values_list("id", flat=True).first()
+ )
+ self._user_github_by_creator: dict[int, Optional[str]] = {}
+
+ def _creator_user_github(self, creator_id: Optional[int]) -> Optional[str]:
+ if creator_id is None:
+ return None
+ if creator_id not in self._user_github_by_creator:
+ uid = UserIntegration.objects.filter(user_id=creator_id, kind="github").values_list("id", flat=True).first()
+ self._user_github_by_creator[creator_id] = str(uid) if uid else None
+ return self._user_github_by_creator[creator_id]
+
+ def resolve(self, task: Task) -> tuple[Optional[int], Optional[str]]:
+ team_int = task.github_integration_id
+ user_int = str(task.github_user_integration_id) if task.github_user_integration_id else None
+ if team_int is None and user_int is None:
+ team_int = self._team_github_id
+ if team_int is None:
+ user_int = self._creator_user_github(task.created_by_id)
+ return team_int, user_int
+
+
+def resolve_github_integration(
+ github_integration_id: Optional[int], github_user_integration_id: Optional[str]
+) -> GitHubIntegrationBase | None:
+ """Instantiate the GitHub integration for the given ids, refreshing an expired token.
+
+ Raises ``ObjectDoesNotExist`` if the id no longer resolves; may also raise on token-refresh failure.
+ """
+ if github_integration_id is not None:
+ integration = GitHubIntegration(Integration.objects.get(id=github_integration_id))
+ if integration.access_token_expired():
+ integration.refresh_access_token()
+ return integration
+ if github_user_integration_id is not None:
+ user_integration = UserGitHubIntegration(UserIntegration.objects.get(id=github_user_integration_id))
+ if user_integration.access_token_expired():
+ user_integration.refresh_access_token()
+ return user_integration
+ return None
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/load_pr_urls.py b/products/tasks/backend/temporal/code_workstreams/activities/load_pr_urls.py
index d924268a509e..455673666d5f 100644
--- a/products/tasks/backend/temporal/code_workstreams/activities/load_pr_urls.py
+++ b/products/tasks/backend/temporal/code_workstreams/activities/load_pr_urls.py
@@ -5,12 +5,11 @@ from django.utils import timezone
from temporalio import activity
-from posthog.models import Integration
from posthog.models.github_integration_base import GitHubIntegrationBase
-from posthog.models.user_integration import UserIntegration
from posthog.temporal.common.utils import close_db_connections
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.temporal.code_workstreams.activities.github_resolution import TeamIntegrationResolver
from products.tasks.backend.temporal.code_workstreams.constants import ACTIVITY_WINDOW, MAX_PRS_PER_TEAM_PER_CYCLE
@@ -60,19 +59,7 @@ def load_team_pr_urls(input: LoadTeamPrUrlsInput) -> LoadTeamPrUrlsOutput:
.order_by("-updated_at")
)
- team_github_id: Optional[int] = (
- Integration.objects.filter(team_id=input.team_id, kind="github").values_list("id", flat=True).first()
- )
- user_github_by_creator: dict[int, Optional[str]] = {}
-
- def creator_user_github(creator_id: Optional[int]) -> Optional[str]:
- if creator_id is None:
- return None
- if creator_id not in user_github_by_creator:
- uid = UserIntegration.objects.filter(user_id=creator_id, kind="github").values_list("id", flat=True).first()
- user_github_by_creator[creator_id] = str(uid) if uid else None
- return user_github_by_creator[creator_id]
-
+ resolver = TeamIntegrationResolver(input.team_id)
seen: dict[str, PrRef] = {}
for run in runs.iterator():
url = (run.output or {}).get("pr_url")
@@ -81,12 +68,7 @@ def load_team_pr_urls(input: LoadTeamPrUrlsInput) -> LoadTeamPrUrlsOutput:
task = run.task
if not _pr_url_belongs_to_task_repo(url, task.repository):
continue
- team_int = task.github_integration_id
- user_int = str(task.github_user_integration_id) if task.github_user_integration_id else None
- if team_int is None and user_int is None:
- team_int = team_github_id
- if team_int is None:
- user_int = creator_user_github(task.created_by_id)
+ team_int, user_int = resolver.resolve(task)
seen[url] = PrRef(pr_url=url, github_integration_id=team_int, github_user_integration_id=user_int)
if len(seen) >= MAX_PRS_PER_TEAM_PER_CYCLE:
break
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py
index debe36715439..c4eb3507ef42 100644
--- a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py
+++ b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py
@@ -11,14 +11,12 @@ from django.utils.dateparse import parse_datetime
import requests
from temporalio import activity
-from posthog.models import Integration
from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError
-from posthog.models.integration import GitHubIntegration
from posthog.models.scoping import team_scope
-from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.temporal.common.utils import close_db_connections
from products.tasks.backend.models import CodePrSnapshot
+from products.tasks.backend.temporal.code_workstreams.activities.github_resolution import resolve_github_integration
from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import PrRef
@@ -40,17 +38,7 @@ def _fingerprint(url: str, updated_at: str | None) -> str:
def _resolve_integration(ref: PrRef) -> GitHubIntegrationBase | None:
- if ref.github_integration_id is not None:
- integration = GitHubIntegration(Integration.objects.get(id=ref.github_integration_id))
- if integration.access_token_expired():
- integration.refresh_access_token()
- return integration
- if ref.github_user_integration_id is not None:
- user_integration = UserGitHubIntegration(UserIntegration.objects.get(id=ref.github_user_integration_id))
- if user_integration.access_token_expired():
- user_integration.refresh_access_token()
- return user_integration
- return None
+ return resolve_github_integration(ref.github_integration_id, ref.github_user_integration_id)
@activity.defn
diff --git a/products/tasks/backend/temporal/code_workstreams/constants.py b/products/tasks/backend/temporal/code_workstreams/constants.py
index 8a203864878d..bb28664e2062 100644
--- a/products/tasks/backend/temporal/code_workstreams/constants.py
+++ b/products/tasks/backend/temporal/code_workstreams/constants.py
@@ -8,4 +8,8 @@ MAX_PRS_PER_TEAM_PER_CYCLE = 50
MAX_TASKS_PER_TEAM = 500
MAX_TEAMS_PER_CYCLE = 2000
+# Caps GitHub API calls per cycle (one per unique repo+branch); separate from
+# MAX_PRS_PER_TEAM_PER_CYCLE because one branch can yield 0..n PRs.
+MAX_BRANCH_QUERIES_PER_TEAM_PER_CYCLE = 30
+
TEAM_FANOUT_CONCURRENCY = 20
diff --git a/products/tasks/backend/temporal/code_workstreams/test_discover_branch_prs.py b/products/tasks/backend/temporal/code_workstreams/test_discover_branch_prs.py
new file mode 100644
index 000000000000..e86aa48f1c72
--- /dev/null
+++ b/products/tasks/backend/temporal/code_workstreams/test_discover_branch_prs.py
@@ -0,0 +1,148 @@
+import random
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.models import Integration, Organization, Team
+
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.temporal.code_workstreams.activities.discover_branch_prs import (
+ DiscoverBranchPrsInput,
+ _collect_branch_candidates,
+ discover_branch_prs,
+)
+
+_RESOLVE = "products.tasks.backend.temporal.code_workstreams.activities.discover_branch_prs.resolve_github_integration"
+
+
+def _make_team():
+ org = Organization.objects.create(name=f"DiscoverOrg-{random.randint(1, 99999)}")
+ team = Team.objects.create(organization=org, name=f"DiscoverTeam-{random.randint(1, 99999)}")
+ # A team-level GitHub integration so TeamIntegrationResolver resolves a usable id.
+ Integration.objects.create(team=team, kind="github", config={}, sensitive_config={}, errors="")
+ return team
+
+
+def _run_on_branch(team, repository, branch, *, pr_url=None, status=TaskRun.Status.COMPLETED):
+ task = Task.objects.create(
+ team=team,
+ title="t",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ repository=repository,
+ )
+ return TaskRun.objects.create(
+ task=task,
+ team=team,
+ status=status,
+ branch=branch,
+ output={"pr_url": pr_url} if pr_url else None,
+ )
+
+
+def _fake_integration(urls_by_branch):
+ fake = MagicMock()
+ fake.find_pull_request_urls_for_branch.side_effect = lambda repo, branch: urls_by_branch.get(branch, [])
+ return fake
+
+
[email protected]_db(transaction=True)
+def test_discovers_pr_for_branch_without_recorded_pr_url(activity_environment):
+ team = _make_team()
+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-x")
+
+ fake = _fake_integration({"posthog-code/feature-x": ["https://github.com/acme/widgets/pull/7"]})
+ with patch(_RESOLVE, return_value=fake):
+ result = activity_environment.run(
+ discover_branch_prs,
+ DiscoverBranchPrsInput(team_id=team.id, known_pr_urls=[], budget=50),
+ )
+
+ assert [ref.pr_url for ref in result.prs] == ["https://github.com/acme/widgets/pull/7"]
+ fake.find_pull_request_urls_for_branch.assert_called_once_with("acme/widgets", "posthog-code/feature-x")
+
+
[email protected]_db(transaction=True)
+def test_skips_pr_urls_already_known(activity_environment):
+ team = _make_team()
+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-x")
+
+ fake = _fake_integration({"posthog-code/feature-x": ["https://github.com/acme/widgets/pull/7"]})
+ with patch(_RESOLVE, return_value=fake):
+ result = activity_environment.run(
+ discover_branch_prs,
+ DiscoverBranchPrsInput(
+ team_id=team.id,
+ known_pr_urls=["https://github.com/acme/widgets/pull/7"],
+ budget=50,
+ ),
+ )
+
+ assert result.prs == []
+
+
[email protected]_db(transaction=True)
+def test_respects_budget(activity_environment):
+ team = _make_team()
+ _run_on_branch(team, "acme/widgets", "branch-a")
+ _run_on_branch(team, "acme/widgets", "branch-b")
+
+ fake = _fake_integration(
+ {
+ "branch-a": ["https://github.com/acme/widgets/pull/1"],
+ "branch-b": ["https://github.com/acme/widgets/pull/2"],
+ }
+ )
+ with patch(_RESOLVE, return_value=fake):
+ result = activity_environment.run(
+ discover_branch_prs,
+ DiscoverBranchPrsInput(team_id=team.id, known_pr_urls=[], budget=1),
+ )
+
+ assert len(result.prs) == 1
+
+
[email protected]_db(transaction=True)
+def test_zero_budget_makes_no_github_calls(activity_environment):
+ team = _make_team()
+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-x")
+
+ fake = _fake_integration({"posthog-code/feature-x": ["https://github.com/acme/widgets/pull/7"]})
+ with patch(_RESOLVE, return_value=fake) as resolve:
+ result = activity_environment.run(
+ discover_branch_prs,
+ DiscoverBranchPrsInput(team_id=team.id, known_pr_urls=[], budget=0),
+ )
+
+ assert result.prs == []
+ resolve.assert_not_called()
+
+
[email protected]_db(transaction=True)
+def test_collect_candidates_dedupes_repo_branch_and_skips_base_and_repoless():
+ team = _make_team()
+ # Same (repo, branch) twice, plus a case-only repo variant — all one candidate.
+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-x")
+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-x")
+ _run_on_branch(team, "AcMe/Widgets", "posthog-code/feature-x")
+ _run_on_branch(team, "acme/widgets", "main") # base branch: skipped
+ _run_on_branch(team, None, "posthog-code/feature-y") # no repo: skipped
+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-z")
+
+ candidates = _collect_branch_candidates(team.id)
+
+ pairs = sorted((c.repository.casefold(), c.branch) for c in candidates)
+ assert pairs == [
+ ("acme/widgets", "posthog-code/feature-x"),
+ ("acme/widgets", "posthog-code/feature-z"),
+ ]
+
+
[email protected]_db(transaction=True)
+def test_collect_candidates_requires_an_integration():
+ org = Organization.objects.create(name=f"NoIntOrg-{random.randint(1, 99999)}")
+ team = Team.objects.create(organization=org, name=f"NoIntTeam-{random.randint(1, 99999)}")
+ # No integration to authenticate with ⇒ no candidate.
+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-x")
+
+ assert _collect_branch_candidates(team.id) == []
diff --git a/products/tasks/backend/temporal/code_workstreams/test_workflow.py b/products/tasks/backend/temporal/code_workstreams/test_workflow.py
index 9163f4d3f7bd..4c74fecd5d04 100644
--- a/products/tasks/backend/temporal/code_workstreams/test_workflow.py
+++ b/products/tasks/backend/temporal/code_workstreams/test_workflow.py
@@ -7,6 +7,7 @@ from temporalio import activity
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
+from products.tasks.backend.temporal.code_workstreams.activities.discover_branch_prs import DiscoverBranchPrsOutput
from products.tasks.backend.temporal.code_workstreams.activities.list_active_teams import ListActiveCodeTeamsOutput
from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import (
LoadTeamPrUrlsInput,
@@ -33,6 +34,11 @@ def _team_pipeline_activities(calls: list[str]):
]
)
+ @activity.defn(name="discover_branch_prs")
+ async def discover(input) -> DiscoverBranchPrsOutput:
+ calls.append("discover")
+ return DiscoverBranchPrsOutput(prs=[])
+
@activity.defn(name="poll_team_pull_requests")
async def poll(input) -> PollTeamPullRequestsOutput:
calls.append("poll")
@@ -43,7 +49,7 @@ def _team_pipeline_activities(calls: list[str]):
calls.append("rebuild")
return RebuildTeamWorkstreamsOutput(users=1, workstreams=2, pruned=0)
- return [load, poll, rebuild]
+ return [load, discover, poll, rebuild]
@pytest.mark.asyncio
@@ -64,7 +70,7 @@ async def test_team_workflow_runs_pipeline_in_order():
id=str(uuid.uuid4()),
task_queue=task_queue,
)
- assert calls == ["load", "poll", "rebuild"]
+ assert calls == ["load", "discover", "poll", "rebuild"]
@pytest.mark.asyncio
@@ -76,6 +82,11 @@ async def test_team_workflow_skips_poll_when_no_prs():
calls.append("load")
return LoadTeamPrUrlsOutput(prs=[])
+ @activity.defn(name="discover_branch_prs")
+ async def discover(input) -> DiscoverBranchPrsOutput:
+ calls.append("discover")
+ return DiscoverBranchPrsOutput(prs=[])
+
@activity.defn(name="poll_team_pull_requests")
async def poll(input) -> PollTeamPullRequestsOutput:
calls.append("poll")
@@ -92,7 +103,7 @@ async def test_team_workflow_skips_poll_when_no_prs():
env.client,
task_queue=task_queue,
workflows=[EvaluateTeamCodeWorkstreamsWorkflow],
- activities=[load, poll, rebuild],
+ activities=[load, discover, poll, rebuild],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
await env.client.execute_workflow(
@@ -101,7 +112,7 @@ async def test_team_workflow_skips_poll_when_no_prs():
id=str(uuid.uuid4()),
task_queue=task_queue,
)
- assert calls == ["load", "rebuild"]
+ assert calls == ["load", "discover", "rebuild"]
@pytest.mark.asyncio
@@ -117,6 +128,10 @@ async def test_dispatcher_fans_out_per_team():
started_teams.append(input.team_id)
return LoadTeamPrUrlsOutput(prs=[])
+ @activity.defn(name="discover_branch_prs")
+ async def discover(input) -> DiscoverBranchPrsOutput:
+ return DiscoverBranchPrsOutput(prs=[])
+
@activity.defn(name="poll_team_pull_requests")
async def poll(input) -> PollTeamPullRequestsOutput:
return PollTeamPullRequestsOutput(polled=0, updated=0, rate_limited=False)
@@ -131,7 +146,7 @@ async def test_dispatcher_fans_out_per_team():
env.client,
task_queue=task_queue,
workflows=[EvaluateCodeWorkstreamsWorkflow, EvaluateTeamCodeWorkstreamsWorkflow],
- activities=[list_teams, load, poll, rebuild],
+ activities=[list_teams, load, discover, poll, rebuild],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
await env.client.execute_workflow(
diff --git a/products/tasks/backend/temporal/code_workstreams/workflow.py b/products/tasks/backend/temporal/code_workstreams/workflow.py
index de683136e26f..c108f3fe48fc 100644
--- a/products/tasks/backend/temporal/code_workstreams/workflow.py
+++ b/products/tasks/backend/temporal/code_workstreams/workflow.py
@@ -8,6 +8,11 @@ from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from posthog.temporal.common.base import PostHogWorkflow
+from products.tasks.backend.temporal.code_workstreams.activities.discover_branch_prs import (
+ DiscoverBranchPrsInput,
+ DiscoverBranchPrsOutput,
+ discover_branch_prs,
+)
from products.tasks.backend.temporal.code_workstreams.activities.list_active_teams import (
ListActiveCodeTeamsOutput,
list_active_code_teams,
@@ -25,7 +30,10 @@ from products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstr
RebuildTeamWorkstreamsInput,
rebuild_team_workstreams,
)
-from products.tasks.backend.temporal.code_workstreams.constants import TEAM_FANOUT_CONCURRENCY
+from products.tasks.backend.temporal.code_workstreams.constants import (
+ MAX_PRS_PER_TEAM_PER_CYCLE,
+ TEAM_FANOUT_CONCURRENCY,
+)
@dataclass
@@ -54,10 +62,29 @@ class EvaluateTeamCodeWorkstreamsWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=3),
)
- if pr_urls.prs:
+ prs = list(pr_urls.prs)
+
+ # Branch discovery surfaces PRs whose run never wrote output.pr_url. It calls GitHub, so it
+ # runs as its own heartbeated activity rather than blocking the DB-only load step.
+ budget = MAX_PRS_PER_TEAM_PER_CYCLE - len(prs)
+ if budget > 0:
+ discovered: DiscoverBranchPrsOutput = await workflow.execute_activity(
+ discover_branch_prs,
+ DiscoverBranchPrsInput(
+ team_id=input.team_id,
+ known_pr_urls=[pr.pr_url for pr in prs],
+ budget=budget,
+ ),
+ start_to_close_timeout=timedelta(minutes=5),
+ heartbeat_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ prs.extend(discovered.prs)
+
+ if prs:
await workflow.execute_activity(
poll_team_pull_requests,
- PollTeamPullRequestsInput(team_id=input.team_id, prs=pr_urls.prs),
+ PollTeamPullRequestsInput(team_id=input.team_id, prs=prs),
start_to_close_timeout=timedelta(minutes=10),
heartbeat_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),