: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(signals): auto-start a PR for every actionable report (#66487)
Michael Matloka0da0ea5f08f5
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex 8f80ba30a314..59ac84376954 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -57,6 +57,11 @@ def _priority_rank(priority: Priority) -> int:return _PRIORITY_RANK[priority]+def _effective_threshold(config: SignalUserAutonomyConfig | None, team_default_priority: Priority) -> Priority:+ """A user's effective autostart threshold: their personal setting if set, else the team default."""+ return Priority(config.autostart_priority) if config and config.autostart_priority else team_default_priority++def _build_autostart_task_description(*, report_id: str, summary: str, repository: str, priority: PriorityAssessment | None) -> str:@@ -163,59 +168,71 @@ def _resolve_autostart_assignee() -> User | None:"""Return the first suggested reviewer whose effective priority threshold allows auto-start.- Walks *reviewers_content* in order (most relevant first). For each reviewer- that maps to an org member with an autonomy config, resolves their effective- threshold (personal setting, falling back to the team default) and checks- whether the report's priority is high enough (lower rank = higher priority).- Returns the first matching ``User``, or ``None`` if nobody qualifies.+ Only used for trusted (pipeline / custom-agent / scout) reviewer lists, which are derived from+ commit authorship rather than user input. User-triggered auto-start does not resolve a named+ reviewer at all — it runs as the triggering user (see `_resolve_triggering_user`), so a user+ can't name a colleague and have the agent run under that colleague's identity.++ Walks *reviewers_content* in order (most relevant first). A reviewer's effective threshold is+ their personal autonomy setting when present, otherwise the team default (itself "all+ priorities"/P4 when the team has no config row). A lower rank means higher priority. Returns+ the first matching ``User``, or ``None`` if no reviewer maps to an org member."""login_to_user = resolve_org_github_login_to_users(team_id, (str(r["github_login"]) for r in reviewers_content if r.get("github_login")))report_rank = _priority_rank(report_priority)- # Map reviewer github logins to user IDs (preserving reviewer order)- candidate_user_ids: list[int] = []+ # Map reviewer github logins to org members, preserving reviewer order (most relevant first).+ candidate_users: list[User] = []for reviewer in reviewers_content:login = reviewer.get("github_login")if not login:continue- login = login.lower()- candidate = login_to_user.get(login)+ candidate = login_to_user.get(login.lower())if isinstance(candidate, User):- candidate_user_ids.append(candidate.id)+ candidate_users.append(candidate)- if not candidate_user_ids:+ if not candidate_users:return None- # organization__team uses the singular related_query_name for each hop, not the- # related_name accessor (organizations/teams), which filter() won't resolve.- users_with_config = {- u.id: u- for u in User.objects.filter(- id__in=candidate_user_ids,- signal_autonomy_config__isnull=False,- organization__team=team_id,- )- .select_related("signal_autonomy_config")- .distinct()+ # Personal autonomy configs are optional: load any that exist to honor a reviewer's own+ # threshold. A reviewer with no config falls back to the team default, which is itself+ # "all priorities" (P4) when the team has no config row (set by the caller).+ configs = {+ c.user_id: c for c in SignalUserAutonomyConfig.objects.filter(user_id__in=[u.id for u in candidate_users])}- # Walk in reviewer order (most relevant first)- for uid in candidate_user_ids:- user = users_with_config.get(uid)- if user is None:- continue- config: SignalUserAutonomyConfig = user.signal_autonomy_config- effective_threshold = (- Priority(config.autostart_priority) if config.autostart_priority else team_default_priority- )- if report_rank <= _priority_rank(effective_threshold):+ for user in candidate_users:+ if report_rank <= _priority_rank(_effective_threshold(configs.get(user.id), team_default_priority)):return userreturn None+def _resolve_triggering_user(+ team_id: int,+ user_id: int,+ report_priority: Priority,+ team_default_priority: Priority,+) -> User | None:+ """Assignee for a *user-triggered* auto-start: the triggering user runs it as themselves.++ When a human edits a report's `suggested_reviewers` (the artefact API), that edit re-runs+ auto-start — but the agent mints a PostHog OAuth token under the task's user, so it must run as+ the person who triggered it, never as a named colleague (that would be reviewer impersonation).+ Returns the triggering user if they're an org member and their effective autonomy threshold+ allows the report's priority, else ``None``.+ """+ user = User.objects.filter(id=user_id, organization__team=team_id).first()+ if user is None:+ return None+ config = SignalUserAutonomyConfig.objects.filter(user_id=user_id).first()+ if _priority_rank(report_priority) <= _priority_rank(_effective_threshold(config, team_default_priority)):+ return user+ return None++async def maybe_autostart_implementation_task(*,team_id: int,@@ -226,13 +243,21 @@ async def maybe_autostart_implementation_task(actionability: ActionabilityAssessment,reviewers_content: list[ReviewerContent],priority: PriorityAssessment | None,+ triggering_user_id: int | None = None,) -> None:"""Start an implementation Task for a SignalReport if autonomy + priority allow it.+ ``triggering_user_id`` is set when a *user edit* of the report's `suggested_reviewers` re-ran+ auto-start: the task then runs as that user (they triggered it), never as a named colleague —+ the agent mints a PostHog OAuth token under the task's user, so running as the assignee would+ let one user act as another (reviewer impersonation). When ``None`` (the pipeline / custom+ agent / scout, whose reviewers come from commit authorship), the assignee is resolved from+ *reviewers_content*.+Idempotent: skipped if an implementation task already started for the report(a `SignalReportTask` implementation gate row), if the report is not immediatelyactionable, if it's already addressed, if priority is missing, if there are no- suggested reviewers, or if no reviewer's autonomy threshold is met. The+ suggested reviewers, or if no reviewer qualifies. The"already started" check is enforced atomically under a row lock in`_create_implementation_task_if_absent`, so concurrent evaluations(reviewer-edit hook, pipeline, custom agent) can't double-start.@@ -269,9 +294,16 @@ async def maybe_autostart_implementation_task(team_config = await SignalTeamConfig.objects.filter(team_id=team_id).afirst()team_default_priority = Priority(team_config.default_autostart_priority) if team_config else Priority.P4- task_user = await database_sync_to_async(_resolve_autostart_assignee, thread_sensitive=False)(- team_id, priority.priority, reviewers_content, team_default_priority- )+ # A user-triggered auto-start runs as the triggering user; otherwise resolve a trusted+ # (commit-authorship) reviewer. Either way the task's user is never an attacker-named colleague.+ if triggering_user_id is not None:+ task_user = await database_sync_to_async(_resolve_triggering_user, thread_sensitive=False)(+ team_id, triggering_user_id, priority.priority, team_default_priority+ )+ else:+ task_user = await database_sync_to_async(_resolve_autostart_assignee, thread_sensitive=False)(+ team_id, priority.priority, reviewers_content, team_default_priority+ )if task_user is None:logger.info("signals auto-start skipped",@@ -317,7 +349,13 @@ async def _latest_artefact_as(report_id: str, artefact_type: str, model_cls: typreturn None-async def _latest_reviewers_content(report_id: str) -> list[ReviewerContent]:+async def _latest_reviewers_content(report_id: str) -> tuple[list[ReviewerContent], int | None]:+ """Latest suggested-reviewers list, plus the id of the user who last edited it (if any).++ The second value is the artefact's user attribution (``created_by_id``): set when a human+ edited it via the artefact API, ``None`` when the pipeline/system wrote it. A user-edited list+ must auto-start as that user, never as a named colleague (reviewer impersonation).+ """artefact = (await SignalReportArtefact.objects.filter(report_id=report_id, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS@@ -326,13 +364,14 @@ async def _latest_reviewers_content(report_id: str) -> list[ReviewerContent]:.afirst())if artefact is None:- return []+ return [], None+ editor_user_id = artefact.created_by_idtry:data = json.loads(artefact.content)except (json.JSONDecodeError, ValueError):- return []+ return [], editor_user_idif not isinstance(data, list):- return []+ return [], editor_user_idreviewers: list[ReviewerContent] = []for entry in data:if isinstance(entry, dict) and entry.get("github_login"):@@ -343,7 +382,7 @@ async def _latest_reviewers_content(report_id: str) -> list[ReviewerContent]:relevant_commits=entry.get("relevant_commits") or [],))- return reviewers+ return reviewers, editor_user_idasync def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str) -> None:@@ -354,6 +393,9 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)latest actionability / priority / repo-selection / suggested-reviewers and delegates to`maybe_autostart_implementation_task`, which is idempotent — it no-ops if an implementationtask already exists for the report.++ When the latest reviewers artefact was user-edited, the task runs as that editing user (not a+ named colleague) — see `_latest_reviewers_content` and `triggering_user_id`."""report = await SignalReport.objects.filter(id=report_id, team_id=team_id).only("title", "summary").afirst()if report is None or not report.title or not report.summary:@@ -391,7 +433,7 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)priority = await _latest_artefact_as(report_id, SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT, PriorityAssessment)- reviewers_content = await _latest_reviewers_content(report_id)+ reviewers_content, editor_user_id = await _latest_reviewers_content(report_id)if not reviewers_content:logger.info("signals auto-start re-eval skipped",@@ -410,4 +452,7 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)actionability=actionability,reviewers_content=reviewers_content,priority=priority,+ # If a user edited the reviewers, run the task as that user — never as a named colleague,+ # which would let one user act under another's PostHog identity (reviewer impersonation).+ triggering_user_id=editor_user_id,)diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.pyindex d8474ee9a4f3..4f38c28a0c20 100644--- a/products/signals/backend/test/test_auto_start.py+++ b/products/signals/backend/test/test_auto_start.py@@ -14,6 +14,7 @@ from products.signals.backend.auto_start import (ReviewerContent,_create_implementation_task_if_absent,_resolve_autostart_assignee,+ _resolve_triggering_user,)from products.signals.backend.models import (SignalReport,@@ -51,21 +52,29 @@ def _reviewer(login: str) -> ReviewerContent:@pytest.mark.django_db@pytest.mark.parametrize(- ("autostart_priority", "report_priority", "expect_match"),+ ("user_autostart_priority", "team_default_priority", "report_priority", "expect_match"),[- (Priority.P2, Priority.P0, True), # report priority at/above threshold → match- (Priority.P1, Priority.P3, False), # report priority below threshold → no match+ (Priority.P2, Priority.P0, Priority.P0, True), # personal config: report at/above threshold → match+ (Priority.P1, Priority.P0, Priority.P3, False), # personal config: report below threshold → no match+ (None, Priority.P4, Priority.P4, True), # no config → team default "all priorities" → match+ (None, Priority.P0, Priority.P3, False), # no config → falls back to a stricter team default → no match],)-def test_resolve_autostart_assignee(organization, team, autostart_priority, report_priority, expect_match):+def test_resolve_autostart_assignee(+ organization, team, user_autostart_priority, team_default_priority, report_priority, expect_match+):+ # Effective threshold is the reviewer's personal config when set, else the team default — so the+ # no-config rows guard against assuming the *personal* default is all-priorities (which would+ # ignore a team's stricter default).user = _create_org_member_with_github("[email protected]", organization, "OctoCat")- SignalUserAutonomyConfig.objects.create(user=user, autostart_priority=autostart_priority.value)+ if user_autostart_priority is not None:+ SignalUserAutonomyConfig.objects.create(user=user, autostart_priority=user_autostart_priority.value)assignee = _resolve_autostart_assignee(team_id=team.id,report_priority=report_priority,reviewers_content=[_reviewer("octocat")],- team_default_priority=Priority.P0,+ team_default_priority=team_default_priority,)if expect_match:@@ -75,6 +84,35 @@ def test_resolve_autostart_assignee(organization, team, autostart_priority, repoassert assignee is None+ ("autostart_priority", "report_priority", "expect_user"),+ [+ (None, Priority.P4, True), # no personal config → team default (P4) → runs as the triggering user+ (Priority.P0, Priority.P3, False), # the triggering user's own strict threshold isn't met+ ],+)+def test_resolve_triggering_user_runs_as_self(organization, team, autostart_priority, report_priority, expect_user):+ # A user-triggered auto-start resolves to the triggering user themselves (subject to their own+ # threshold), never a named colleague — the core reviewer-impersonation guard.+ user = _create_org_member_with_github("[email protected]", organization, "OctoCat")+ if autostart_priority is not None:+ SignalUserAutonomyConfig.objects.create(user=user, autostart_priority=autostart_priority.value)++ resolved = _resolve_triggering_user(+ team_id=team.id,+ user_id=user.id,+ report_priority=report_priority,+ team_default_priority=Priority.P4,+ )++ if expect_user:+ assert resolved is not None+ assert resolved.id == user.id+ else:+ assert resolved is None++@pytest.mark.django_dbdef test_create_implementation_task_if_absent_is_idempotent(organization, team):# The locked create guards against duplicate auto-start tasks: a second evaluation thatdiff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.pyindex 475243a0c866..49f0c4f5633a 100644--- a/products/signals/backend/test/test_signal_report_artefact_api.py+++ b/products/signals/backend/test/test_signal_report_artefact_api.py@@ -272,6 +272,9 @@ class TestSignalReportArtefactViewSet(APIBaseTest):kwargs = mock_impl.call_args.kwargsassert kwargs["repository"] == "acme/repo"assert {r["github_login"] for r in kwargs["reviewers_content"]} == {"alice", "bob"}+ # The edit must auto-start as the *editing* user (the API caller), never a named reviewer,+ # so one user can't run the agent under another's identity (reviewer impersonation).+ assert kwargs["triggering_user_id"] == self.user.iddef test_put_empty_list_clears_content(self):report = self._create_report()