: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(tasks): scope Home tab task selection per-user, not per-team (#70993)
Peter Kirkham2a4af1eb8157
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py b/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.pyindex 482f4849ee7e..ec7f84e17703 100644--- a/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py+++ b/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py@@ -1,9 +1,11 @@+import uuidfrom collections import defaultdictfrom dataclasses import dataclassfrom datetime import UTC, datetimefrom typing import Optional-from django.db.models import Max, Q+from django.db.models import F, Max, Q, Window+from django.db.models.functions import RowNumberfrom django.utils import timezonefrom temporalio import activity@@ -14,6 +16,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.tasks.backend.logic.code_workstreams.classify import pick_primary_situationfrom products.tasks.backend.logic.code_workstreams.grouping import (+ DEFAULT_BASE_BRANCHES,PrInput,TaskInput,Workstream,@@ -21,7 +24,11 @@ from products.tasks.backend.logic.code_workstreams.grouping import (build_workstreams,)from products.tasks.backend.models import CodePrSnapshot, CodeWorkstream, Task, TaskRun-from products.tasks.backend.temporal.code_workstreams.constants import ACTIVITY_WINDOW, MAX_TASKS_PER_TEAM+from products.tasks.backend.temporal.code_workstreams.constants import (+ ACTIVITY_WINDOW,+ MAX_TASKS_PER_TEAM,+ MAX_TASKS_PER_USER,+)from products.tasks.backend.temporal.process_task.utils import parse_run_state@@ -147,6 +154,44 @@ def _github_logins_by_user(user_ids: list[int]) -> dict[int, set[str]]:return logins+def _select_recent_task_ids(team_id: int, cutoff: datetime) -> list[uuid.UUID]:+ # Rank each user's tasks by most-recent run activity and keep only their freshest+ # MAX_TASKS_PER_USER, so one high-volume user can't evict another user's tasks. The+ # MAX_TASKS_PER_TEAM cap then bounds the whole team's set, still favouring recency.+ # Candidates come from runs inside the activity window so the query's working set+ # scales with recent activity, not the team's all-time task count. Only runs that+ # could form a workstream (a PR, or a branch that isn't a default base — see+ # workstream_key) consume cap slots: tasks that can never produce a lane must not+ # evict ones that can. task_id tie-breakers keep ranking stable across rebuilds+ # when activity timestamps collide, so the cap cutoff can't flicker and prune an+ # unchanged task's workstream.+ return list(+ TaskRun.objects.filter(+ team_id=team_id,+ updated_at__gte=cutoff,+ task__archived=False,+ task__deleted=False,+ task__created_by__isnull=False,+ )+ .filter(+ Q(output__pr_url__isnull=False)+ | (Q(branch__isnull=False) & ~Q(branch="") & ~Q(branch__in=DEFAULT_BASE_BRANCHES))+ )+ .values("task_id", "task__created_by_id")+ .annotate(last_activity=Max("updated_at"))+ .annotate(+ user_rank=Window(+ expression=RowNumber(),+ partition_by=F("task__created_by_id"),+ order_by=(F("last_activity").desc(), F("task_id").asc()),+ )+ )+ .filter(user_rank__lte=MAX_TASKS_PER_USER)+ .order_by("-last_activity", "task_id")+ .values_list("task_id", flat=True)[:MAX_TASKS_PER_TEAM]+ )++@activity.defn@close_db_connectionsdef rebuild_team_workstreams(input: RebuildTeamWorkstreamsInput) -> RebuildTeamWorkstreamsOutput:@@ -154,15 +199,7 @@ def rebuild_team_workstreams(input: RebuildTeamWorkstreamsInput) -> RebuildTeamWcutoff = now - ACTIVITY_WINDOWnow_ms = _epoch_ms(now)- # Group by task and order by most-recent activity so the MAX_TASKS_PER_TEAM cap deterministically- # keeps the freshest tasks instead of an arbitrary slice that flickers between cycles.- recent_task_ids = [- row["task_id"]- for row in TaskRun.objects.filter(team_id=input.team_id, updated_at__gte=cutoff)- .values("task_id")- .annotate(last_activity=Max("updated_at"))- .order_by("-last_activity")[:MAX_TASKS_PER_TEAM]- ]+ recent_task_ids = _select_recent_task_ids(input.team_id, cutoff)tasks = list(Task.objects.filter(id__in=recent_task_ids, team_id=input.team_id, archived=False, deleted=False).select_related("created_by")diff --git a/products/tasks/backend/temporal/code_workstreams/constants.py b/products/tasks/backend/temporal/code_workstreams/constants.pyindex bb28664e2062..e93d06dbb919 100644--- a/products/tasks/backend/temporal/code_workstreams/constants.py+++ b/products/tasks/backend/temporal/code_workstreams/constants.py@@ -5,7 +5,10 @@ HOME_TAB_FLAG = "posthog-code-home-tab"ACTIVITY_WINDOW = timedelta(days=30)MAX_PRS_PER_TEAM_PER_CYCLE = 50-MAX_TASKS_PER_TEAM = 500+# Per-user cap keeps one high-volume user from evicting other users' tasks from the Home tab;+# the per-team cap bounds the total work each rebuild cycle does for a team.+MAX_TASKS_PER_USER = 50+MAX_TASKS_PER_TEAM = 3000MAX_TEAMS_PER_CYCLE = 2000# Caps GitHub API calls per cycle (one per unique repo+branch); separate fromdiff --git a/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py b/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.pyindex b7f23e009c20..067763f63e05 100644--- a/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py+++ b/products/tasks/backend/temporal/code_workstreams/test_rebuild_workstreams.py@@ -1,13 +1,24 @@-from datetime import UTC, datetime+import random+from collections import Counter+from datetime import UTC, datetime, timedeltaimport pytest+from freezegun import freeze_time+from unittest.mock import patch-from products.tasks.backend.models import CodePrSnapshot+from django.utils import timezone++from posthog.models import Organization, Team, User++from products.tasks.backend.models import CodePrSnapshot, Task, TaskRun+from products.tasks.backend.temporal.code_workstreams.activities import rebuild_workstreamsfrom products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstreams import (_branch_resolution_pref,_build_pr_input,_repo_from_pr_url,+ _select_recent_task_ids,)+from products.tasks.backend.temporal.code_workstreams.constants import ACTIVITY_WINDOWfrom products.tasks.backend.temporal.process_task.utils import parse_run_state@@ -114,3 +125,121 @@ def test_build_pr_input_is_requested_reviewer_requires_identity_match():pr = _build_pr_input(_snapshot(requested_reviewer_logins=requested_reviewer_logins), user_github_logins)assert pr.is_current_user_requested_reviewer is expected+++def _org() -> Organization:+ return Organization.objects.create(name=f"WsOrg-{random.randint(1, 10**9)}")+++def _team(org: Organization) -> Team:+ return Team.objects.create(organization=org, name=f"WsTeam-{random.randint(1, 10**9)}")+++def _user(org: Organization) -> User:+ return User.objects.create_and_join(org, f"u{random.randint(1, 10**9)}@example.com", None)+++def _task_with_run_at(+ team: Team,+ user: User,+ activity_at: datetime,+ branch: str | None = "feat/home",+ output: dict | None = None,+) -> Task:+ task = Task.objects.create(+ team=team, created_by=user, title="t", description="d", origin_product=Task.OriginProduct.USER_CREATED+ )+ run = TaskRun.objects.create(task=task, team=team, status=TaskRun.Status.COMPLETED, branch=branch, output=output)+ # updated_at is auto_now, so set the activity timestamp with a bulk update to bypass it.+ TaskRun.objects.filter(id=run.id).update(updated_at=activity_at)+ return task+++@freeze_time("2026-06-01")+def test_select_recent_task_ids_caps_per_user_and_keeps_low_volume_user():+ org = _org()+ team = _team(org)+ heavy = _user(org)+ light = _user(org)+ now = timezone.now()++ # Heavy user floods the team with 55 very recent tasks; only its freshest 50 should survive.+ heavy_tasks = [_task_with_run_at(team, heavy, now - timedelta(minutes=i)) for i in range(1, 56)]+ # Light user's older tasks must not be evicted by the heavy user's firehose.+ light_tasks = [_task_with_run_at(team, light, now - timedelta(hours=5, minutes=i)) for i in range(1, 4)]++ selected = set(_select_recent_task_ids(team.id, now - ACTIVITY_WINDOW))++ by_user = Counter(t.created_by_id for t in heavy_tasks + light_tasks if t.id in selected)+ assert by_user[heavy.id] == 50+ assert by_user[light.id] == 3++ # The dropped heavy-user tasks are its five oldest.+ dropped = {t.id for t in heavy_tasks if t.id not in selected}+ assert dropped == {t.id for t in heavy_tasks[-5:]}+++@freeze_time("2026-06-01")+def test_select_recent_task_ids_applies_team_cap_across_users():+ org = _org()+ team = _team(org)+ now = timezone.now()+ for _ in range(3):+ user = _user(org)+ for i in range(1, 5):+ _task_with_run_at(team, user, now - timedelta(minutes=i))++ # Per-user cap admits all 12 tasks; the team cap is the ceiling that bounds the set.+ with patch.object(rebuild_workstreams, "MAX_TASKS_PER_TEAM", 7):+ selected = _select_recent_task_ids(team.id, now - ACTIVITY_WINDOW)++ assert len(selected) == 7+++@freeze_time("2026-06-01")+def test_select_recent_task_ids_breaks_activity_ties_deterministically():+ org = _org()+ team = _team(org)+ user = _user(org)+ now = timezone.now()++ # More tied tasks than the cap: without a stable tie-breaker the rank-50 cutoff+ # shuffles between rebuilds and the prune deletes an unchanged task's workstream.+ tied = [_task_with_run_at(team, user, now - timedelta(hours=1)) for _ in range(55)]++ selected = _select_recent_task_ids(team.id, now - ACTIVITY_WINDOW)++ assert selected == sorted(t.id for t in tied)[:50]+++@freeze_time("2026-06-01")+def test_select_recent_task_ids_ignores_tasks_that_cannot_form_workstreams():+ org = _org()+ team = _team(org)+ user = _user(org)+ now = timezone.now()++ # A fresh burst of lane-ineligible tasks (no PR, no feature branch) exceeds the cap...+ junk = [+ _task_with_run_at(team, user, now - timedelta(minutes=i), branch=branch)+ for i, branch in enumerate([None, "", "master", "main"] * 13, start=1)+ ]+ # ...but must not consume slots and evict the user's older lane-bearing tasks.+ branch_task = _task_with_run_at(team, user, now - timedelta(hours=2))+ pr_task = _task_with_run_at(+ team,+ user,+ now - timedelta(hours=3),+ branch=None,+ output={"pr_url": "https://github.com/org/repo/pull/1"},+ )++ selected = set(_select_recent_task_ids(team.id, now - ACTIVITY_WINDOW))++ assert branch_task.id in selected+ assert pr_task.id in selected+ assert selected.isdisjoint({t.id for t in junk})