: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(signals): claim manual implement runs for the person who started them (#129694)
Dylan Martinff0d24024454
diff --git a/products/signals/backend/facade/report_tasks.py b/products/signals/backend/facade/report_tasks.pyindex 83baf862e05b..38adaa9a204c 100644--- a/products/signals/backend/facade/report_tasks.py+++ b/products/signals/backend/facade/report_tasks.py@@ -15,6 +15,7 @@ __all__ = ["delete_report_task_artefact","enforce_report_implementation_rerun_cap","enforce_report_task_cap",+ "queue_task_handoff_claims","is_pull_request_run_request","is_report_implementation_task","record_report_task",@@ -75,6 +76,13 @@ def enforce_report_implementation_rerun_cap(*, team_id: int, report_id: str, tastask_run_artefacts.enforce_report_implementation_rerun_cap(team_id=team_id, report_id=report_id, task_id=task_id)+def queue_task_handoff_claims(*, team_id: int, task_id: str, previous_user_id: int) -> None:+ """Queue moving the report claims a handed-off task works under to its owner. Call after the handoff commits."""+ from products.signals.backend.handoff_claim_tasks import reconcile_task_handoff_claims++ reconcile_task_handoff_claims.delay(team_id=team_id, task_id=task_id, previous_user_id=previous_user_id)++def release_quota_cancelled_implementation(*, team_id: int, task_id: str) -> list[str]:"""Remove the implementation records of a quota-cancelled task so its reports can run again.diff --git a/products/signals/backend/handoff_claim_tasks.py b/products/signals/backend/handoff_claim_tasks.pynew file mode 100644index 000000000000..751f9b855289--- /dev/null+++ b/products/signals/backend/handoff_claim_tasks.py@@ -0,0 +1,13 @@+from celery import shared_task++from posthog.models.scoping import with_team_scope++from products.signals.backend.report_assignments import hand_off_task_claims+++@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5)+@with_team_scope()+def reconcile_task_handoff_claims(team_id: int, task_id: str, previous_user_id: int) -> None:+ # The handoff has already committed, so a failed transfer must retry here; it reads the current owner, so a+ # retry after a later handoff still lands on the right person.+ hand_off_task_claims(team_id=team_id, task_id=task_id, previous_user_id=previous_user_id)diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.pyindex 55a1f6ff39b1..0009ec381390 100644--- a/products/signals/backend/report_assignments.py+++ b/products/signals/backend/report_assignments.py@@ -44,6 +44,7 @@ from products.signals.backend.report_claims import (actor_works_under_claim,claim_from_artefact,get_active_claim,+ is_user_claim_of,is_user_claim_of_task_creator,)from products.signals.backend.report_monitoring_attempts import complete_implementation@@ -139,15 +140,16 @@ def assignment_snapshot(return {"assignee": assignee, "implementation_pr": implementation_pr}-def create_claim(report: SignalReport, actor: ArtefactAttribution) -> ReportClaim:+def create_claim(report: SignalReport, actor: ArtefactAttribution, *, task_id: str | None = None) -> ReportClaim:claim = SignalReportArtefact.add_log(team_id=report.team_id,report_id=str(report.id),content=WorkClaim(display_name=claim_display_name(report, actor)),attribution=actor,)- if actor.task_id:- _associate_task_with_claim(report, actor.task_id, claim)+ task_id = actor.task_id or task_id+ if task_id:+ _associate_task_with_claim(report, task_id, claim)return claim_from_artefact(claim)@@ -158,16 +160,17 @@ def _associate_task_with_claim(report: SignalReport, task_id: str, claim: Signaltype="task_run",task_id=task_id,)- if not associations.exists():- SignalReportArtefact.add_log(- team_id=report.team_id,- report_id=str(report.id),- content=TaskRunArtefact(task_id=task_id, product="tasks", type="agent_run"),- attribution=ArtefactAttribution.from_task(task_id),- claim_id=str(claim.id),- )- else:- associations.filter(claim__isnull=True).update(claim=claim)+ if associations.filter(claim__isnull=True).update(claim=claim) or associations.filter(claim=claim).exists():+ return+ # A rerun under a new claim needs its own association, so the run's PR links to the current claim and not+ # to one an earlier run released.+ SignalReportArtefact.add_log(+ team_id=report.team_id,+ report_id=str(report.id),+ content=TaskRunArtefact(task_id=task_id, product="tasks", type="agent_run"),+ attribution=ArtefactAttribution.from_task(task_id),+ claim_id=str(claim.id),+ )def assignment_actor(assignment: SignalReportAssignment) -> ArtefactAttribution:@@ -194,7 +197,13 @@ def release_claim(claim: ReportClaim, actor: ArtefactAttribution, *, takeover: b)-def claim_report_for_task(*, team_id: int, report_id: str, task_id: str) -> ReportClaim:+def claim_report_for_task(*, team_id: int, report_id: str, task_id: str, for_task_creator: bool = False) -> ReportClaim:+ """Claim the report for the work of a task, unless the task already works under the active claim.++ With `for_task_creator`, a new claim goes to the person who started the task, because that+ person chose to do the work, and readers hide task claims. A task without a creator keeps a+ task claim.+ """with transaction.atomic():report = SignalReport.objects.select_for_update().get(id=report_id, team_id=team_id)import_report_pull_requests(report)@@ -209,7 +218,49 @@ def claim_report_for_task(*, team_id: int, report_id: str, task_id: str) -> Reporeturn claimif claim is not None and not actor_owns_claim(claim, actor):raise ReportClaimConflict("This report already has an active claim.")- return claim or create_claim(report, actor)+ if claim is not None:+ return claim+ creator_id = tasks_facade.get_task_creator_ids([task_id], [team_id]).get(task_id) if for_task_creator else None+ if creator_id is None:+ return create_claim(report, actor)+ return create_claim(report, ArtefactAttribution.from_user(creator_id), task_id=task_id)+++def hand_off_task_claims(*, team_id: int, task_id: str, previous_user_id: int) -> None:+ """Move the report claims a task works under from its previous owner to the person who owns it now.++ The task's runs work under its creator's claim, so a claim left with the previous owner would refuse+ every later run of the task. Call after the handoff commits: each report is locked here, and holding+ the task's lock at the same time would invert the lock order a rerun takes.+ """+ report_ids = (+ SignalReportArtefact.objects.filter(team_id=team_id, type="task_run", task_id=task_id, claim__isnull=False)+ .values_list("report_id", flat=True)+ .distinct()+ )+ # A later handoff can commit before this runs, so the claim goes to whoever owns the task now.+ current_owner_id = tasks_facade.get_task_creator_ids([task_id], [team_id]).get(task_id)+ if current_owner_id is None or current_owner_id == previous_user_id:+ return+ target = ArtefactAttribution.from_user(current_owner_id)+ for report_id in list(report_ids):+ with transaction.atomic():+ report = SignalReport.objects.select_for_update().filter(id=report_id, team_id=team_id).first()+ claim = get_active_claim(team_id=team_id, report_id=str(report_id)) if report is not None else None+ if report is None or claim is None or not is_user_claim_of(claim, previous_user_id):+ continue+ tasks_under_claim = {+ str(other)+ for other in SignalReportArtefact.objects.filter(+ team_id=team_id, type="task_run", claim_id=claim.claim_id+ ).values_list("task_id", flat=True)+ }+ # Another task of the previous owner, such as a replacement implementation, works under the same+ # claim and still needs it.+ if tasks_under_claim != {task_id}:+ continue+ release_claim(claim, target, takeover=True)+ create_claim(report, target, task_id=task_id)def _pull_request_details(team_id: int, pr_url: str, *, raise_on_error: bool = False) -> PullRequestDetails:@@ -343,14 +394,25 @@ def sync_task_pull_request_to_assignments(.order_by("-created_at", "-id").first())- claim_id = str(historical.id) if historical else None+ # A task that works under its creator's claim holds no claim of its own, so its PR+ # goes to the claim that its run artefact is attached to.+ claim_id = (+ historical.id+ if historical+ else SignalReportArtefact.objects.filter(+ team_id=team_id, report_id=report.id, type="task_run", task_id=task_id, claim__isnull=False+ )+ .order_by("-created_at", "-id")+ .values_list("claim_id", flat=True)+ .first()+ )link_pull_request(report=report,details=PullRequestDetails(url=pr_url, repository=repository, number=parsed.number, state=state, merged=merged),actor=actor,- claim_id=claim_id,+ claim_id=str(claim_id) if claim_id else None,state_source=PullRequestStateSource.TASK_OUTPUT,)return len(reports)diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.pyindex ca21ba1ee2a7..ee13a6f4205a 100644--- a/products/signals/backend/task_run_artefacts.py+++ b/products/signals/backend/task_run_artefacts.py@@ -19,6 +19,8 @@ from enum import StrEnumfrom django.db import transaction+from pydantic import ValidationError+from products.signals.backend.artefact_schemas import (SIGNALS_PRODUCT,TASK_RUN_TYPE_DISCUSSION,@@ -339,7 +341,40 @@ def enforce_report_implementation_rerun_cap(*, team_id: int, report_id: str, tasclaim = _implementation_slot_claim(team_id=team_id, report_id=report_id, exclude_task_id=task_id)if claim is not None:raise ReportTaskCapExceeded(kind=TASK_RUN_TYPE_IMPLEMENTATION, detail=claim.detail)- claim_report_for_task(team_id=team_id, report_id=report_id, task_id=task_id)+ claim_report_for_task(+ team_id=team_id,+ report_id=report_id,+ task_id=task_id,+ for_task_creator=implementation_started_by_person(team_id=team_id, report_id=report_id, task_id=task_id),+ )+++def implementation_started_by_person(*, team_id: int, report_id: str, task_id: str) -> bool:+ """Whether a person started this implementation task by hand, rather than auto-start.++ Auto-start stamps its generated branch on the run artefact of every run it starts, and the+ manual start-task API leaves it unset. One stamped run makes the task automatic, because+ auto-start runs a task as a suggested reviewer who never took the work on. A row that does not+ parse also counts as automatic, so that no claim names a person without evidence.+ """+ rows = SignalReportArtefact.objects.filter(+ team_id=team_id,+ report_id=report_id,+ type=SignalReportArtefact.ArtefactType.TASK_RUN,+ task_id=task_id,+ ).values_list("content", flat=True)+ found = False+ for content in rows:+ try:+ artefact = TaskRunArtefact.model_validate_json(content)+ except ValidationError:+ return False+ if artefact.type != TASK_RUN_TYPE_IMPLEMENTATION:+ continue+ if artefact.automation_branch is not None:+ return False+ found = True+ return founddef record_implementation_task(@@ -387,7 +422,12 @@ def record_implementation_task(attribution=ArtefactAttribution.from_task(task_id),)try:- claim_report_for_task(team_id=team_id, report_id=report_id, task_id=task_id)+ claim_report_for_task(+ team_id=team_id,+ report_id=report_id,+ task_id=task_id,+ for_task_creator=implementation_started_by_person(team_id=team_id, report_id=report_id, task_id=task_id),+ )except ReportClaimConflict as error:raise ReportTaskCapExceeded(kind=TASK_RUN_TYPE_IMPLEMENTATION, detail=str(error)) from errorreturn artefactdiff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 5a0dbd3377b0..8bc4a7e5f2c6 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -41,6 +41,7 @@ from products.signals.backend.first_report_notification_tasks import (sweep_first_report_notifications as sweep_first_report_notifications,)from products.signals.backend.github_writeback_tasks import post_source_issue_links as post_source_issue_links+from products.signals.backend.handoff_claim_tasks import reconcile_task_handoff_claims as reconcile_task_handoff_claimsfrom products.signals.backend.implementation_dispatch_tasks import (dispatch_implementation_replacement as dispatch_implementation_replacement,sweep_implementation_dispatches as sweep_implementation_dispatches,diff --git a/products/signals/backend/test/test_task_run_artefacts.py b/products/signals/backend/test/test_task_run_artefacts.pyindex cee0a31e3ed2..e30944ecf013 100644--- a/products/signals/backend/test/test_task_run_artefacts.py+++ b/products/signals/backend/test/test_task_run_artefacts.py@@ -7,6 +7,8 @@ from django.db import transactionfrom parameterized import parameterized+from posthog.models.user import User+from products.signals.backend.billing import first_billable_pr_run_atfrom products.signals.backend.custom_agent.persistence import create_custom_agent_ready_reportfrom products.signals.backend.custom_agent.schemas import CustomAgentFinalReport@@ -19,7 +21,11 @@ from products.signals.backend.models import (SignalReportPullRequest,SignalReportTask,)-from products.signals.backend.report_assignments import create_claim, sync_task_pull_request_to_assignments+from products.signals.backend.report_assignments import (+ create_claim,+ release_claim,+ sync_task_pull_request_to_assignments,+)from products.signals.backend.report_claims import get_active_claimfrom products.signals.backend.report_generation.research import (ActionabilityAssessment,@@ -58,12 +64,13 @@ class TestTaskRunArtefacts(BaseTest):total_weight=1.0,)- def _task(self) -> Task:+ def _task(self, created_by: User | None = None) -> Task:return Task.objects.create(team=self.team,title="task",description="desc",origin_product=Task.OriginProduct.SIGNAL_REPORT,+ created_by=created_by,)def _task_run_artefacts(self, report: SignalReport) -> list[SignalReportArtefact]:@@ -167,10 +174,21 @@ class TestTaskRunArtefacts(BaseTest):# The custom product's "implementation" row doesn't count as a signals implementation.assert signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION) == []- def test_record_implementation_task_writes_gate_row_and_artefact(self):+ @parameterized.expand(+ [+ ("manual_start_claims_for_the_creator", True, None, SignalActorKind.USER),+ ("manual_start_without_creator_keeps_a_task_claim", False, None, SignalActorKind.TASK),+ ("auto_start_keeps_a_task_claim", True, "posthog/self-driving-fix", SignalActorKind.TASK),+ ]+ )+ def test_record_implementation_task_writes_gate_row_and_artefact(+ self, _name, has_creator, automation_branch, expected_kind+ ):report = self._report()- task = self._task()- record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))+ task = self._task(created_by=self.user if has_creator else None)+ record_implementation_task(+ team_id=self.team.id, report_id=str(report.id), task_id=str(task.id), automation_branch=automation_branch+ )# Both the legacy SignalReportTask gate row and the task_run work-log artefact are written.assert SignalReportTask.objects.filter(@@ -179,13 +197,50 @@ class TestTaskRunArtefacts(BaseTest):assert signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION) == [str(task.id)]assignment = get_active_claim(team_id=self.team.id, report_id=report.id)assert assignment is not None- assert assignment.actor_kind == SignalActorKind.TASK- assert assignment.actor_task_id == task.id+ assert assignment.actor_kind == expected_kind+ if expected_kind == SignalActorKind.USER:+ assert assignment.actor_user_id == self.user.id+ assert assignment.actor_task_id is None+ else:+ assert assignment.actor_task_id == task.id+ task_run = SignalReportArtefact.objects.get(report=report, type="task_run", task_id=task.id)+ assert task_run.claim_id == assignment.claim_id# Idempotent on the gate row for the same task — re-recording doesn't duplicate the link.- record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))+ record_implementation_task(+ team_id=self.team.id, report_id=str(report.id), task_id=str(task.id), automation_branch=automation_branch+ )assert SignalReportTask.objects.filter(report=report, task=task).count() == 1+ # A rerun after the run released its claim claims the report again for the same actor.+ release_claim(assignment, ArtefactAttribution.system())+ with transaction.atomic():+ enforce_report_implementation_rerun_cap(+ team_id=self.team.id, report_id=str(report.id), task_id=str(task.id)+ )+ rerun_claim = get_active_claim(team_id=self.team.id, report_id=report.id)+ assert rerun_claim is not None+ assert rerun_claim.claim_id != assignment.claim_id+ assert rerun_claim.actor_kind == expected_kind++ def test_rerun_keeps_the_task_claim_of_a_manual_task(self):+ report = self._report()+ task = self._task(created_by=self.user)+ record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))+ user_claim = get_active_claim(team_id=self.team.id, report_id=report.id)+ assert user_claim is not None+ release_claim(user_claim, ArtefactAttribution.system())+ task_claim = create_claim(report, ArtefactAttribution.from_task(str(task.id)))++ with transaction.atomic():+ enforce_report_implementation_rerun_cap(+ team_id=self.team.id, report_id=str(report.id), task_id=str(task.id)+ )++ assignment = get_active_claim(team_id=self.team.id, report_id=report.id)+ assert assignment is not None+ assert assignment.claim_id == task_claim.claim_id+def test_claimer_starts_implementation_under_their_own_claim(self):report = self._report()claimer = self._create_user("[email protected]")@@ -235,10 +290,34 @@ class TestTaskRunArtefacts(BaseTest):assert assignment is not Noneassert assignment.actor_user_id == claimer.id- @parameterized.expand([(False,), (True,)])- def test_task_run_pr_is_linked_to_the_claim(self, attach_after_merge):+ def test_rerun_pr_links_to_the_claim_the_rerun_took(self):report = self._report()- task = self._task()+ task = self._task(created_by=self.user)+ record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))+ first_claim = get_active_claim(team_id=self.team.id, report_id=report.id)+ assert first_claim is not None+ release_claim(first_claim, ArtefactAttribution.system())+ with transaction.atomic():+ enforce_report_implementation_rerun_cap(+ team_id=self.team.id, report_id=str(report.id), task_id=str(task.id)+ )+ rerun_claim = get_active_claim(team_id=self.team.id, report_id=report.id)+ assert rerun_claim is not None++ TaskRun.objects.create(+ team=self.team,+ task=task,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": "https://github.com/PostHog/posthog/pull/44", "pr_state": "open"},+ )++ pr_artefact = SignalReportArtefact.objects.get(report=report, type="pull_request")+ assert pr_artefact.claim_id == rerun_claim.claim_id++ @parameterized.expand([(False, False), (True, False), (False, True)])+ def test_task_run_pr_is_linked_to_the_claim(self, attach_after_merge, has_creator):+ report = self._report()+ task = self._task(created_by=self.user if has_creator else None)record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))if attach_after_merge:diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.tsindex 59a027333f5c..6e2344645ee1 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts@@ -139,7 +139,7 @@ const REPORT_STATE_INSTRUCTIONS = `Keep the report's own state honest while you- Opening the PR is enough by itself. The PR is linked to the report for you, and merging it resolves the report. Do NOT set the state to resolved because you opened a PR: that closes the PR you just opened.- If the work is finished without a PR, set the state to resolved with the reason that fits (\`fixed_outside_posthog\`, \`pr_merged\`, or \`already_fixed\`) and a short note that says what you did.- If the report holds no work to do, set the state to suppressed with the reason that says why (\`report_unclear\`, \`analysis_wrong\`, \`wrong_repo\` with \`corrected_repository\`, \`wontfix_intentional\`, \`wontfix_irrelevant\`, or \`other\`) and a short note, then release your claim: suppressing does not release it for you. A report sent to the wrong person still holds work, so do not suppress it for that reason.-- If you stop for any other reason, release your claim on the report, so it does not look like work is still in flight.`+- If you stop for any other reason, release your claim on the report, so it does not look like work is still in flight. When the claim belongs to the person who started you, keep it: it is their claim, and only they can release it.`export function buildCreatePrReportPrompt(report: SignalReport, feedback?: string): string {const base = `Act on PostHog Inbox report "${report.title ?? report.id}" (id ${report.id}). Investigate the root cause using the report's contributing findings, implement the fix, and open a PR.${diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex f45706282c0f..409489419745 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -1406,16 +1406,26 @@ describe('inboxReportDetailLogic', () => {expect(logic.values.reportTaskToOpen).toEqual(openTaskIndex === null ? null : tasks[openTaskIndex])})- it('refreshes the artefact log once a PR task starts', async () => {+ it('refreshes the artefact log and the claimant once a PR task starts', async () => {await expectLogic(logic).toFinishAllListeners()const beforeKickoff = artefactRequests+ const reloadReport = jest.fn()+ const sceneSpy = jest.spyOn(inboxSceneLogic, 'findMounted').mockReturnValue({+ values: { selectedReportId: REPORT.id, selectedReportLoading: false },+ actions: { loadSelectedReport: reloadReport },+ } as unknown as ReturnType<typeof inboxSceneLogic.build>)- // Without this the gate keeps reading the pre-kickoff task list, so a ready report offers- // Create PR a second time and the server answers the press with a 429.- logic.actions.createPrSuccess()- await expectLogic(logic).toFinishAllListeners()+ try {+ // Without this the gate keeps reading the pre-kickoff task list, so a ready report offers+ // Create PR a second time and the server answers the press with a 429.+ logic.actions.createPrSuccess()+ await expectLogic(logic).toFinishAllListeners()- expect(artefactRequests).toBe(beforeKickoff + 1)+ expect(artefactRequests).toBe(beforeKickoff + 1)+ expect(reloadReport).toHaveBeenCalledWith({ id: REPORT.id })+ } finally {+ sceneSpy.mockRestore()+ }})it.each([SignalReportStatus.RESOLVED, SignalReportStatus.CLOSED, SignalReportStatus.SUPPRESSED])(diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex d0f32d5c500d..464ea6049ccd 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -2262,6 +2262,8 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([// never gets one going.createPrSuccess: () => {actions.loadReportArtefacts()+ // The task claims the report for the person who pressed Create PR, so reload the claimant.+ refreshSelectedReport(props.reportId)},discussReportSuccess: () => {actions.loadReportArtefacts()diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex db93c7769932..5e087c1626ef 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -8,6 +8,7 @@ from collections.abc import Callable, Collection, Iterable, Iterator, Mapping, Sfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, field, replacefrom datetime import UTC, datetime, timedelta+from functools import partialfrom pathlib import PurePosixPathfrom typing import TYPE_CHECKING, Any, Literal, TypeVar, castfrom urllib.parse import urlparse@@ -8693,6 +8694,19 @@ def handoff_task(}locked.state[TASK_OWNERSHIP_VERSION_STATE_KEY] = str(uuid4())locked.save()+ from products.signals.backend.facade.report_tasks import ( # noqa: PLC0415 — cross-product write kept off the api import path+ queue_task_handoff_claims,+ )++ # After commit, so the report locks it takes are never waited on while this task row is locked.+ transaction.on_commit(+ partial(+ queue_task_handoff_claims,+ team_id=team_id,+ task_id=str(locked.id),+ previous_user_id=user_id,+ )+ )message = TaskThreadMessage.objects.for_team(team_id).create(team_id=team_id,task_id=locked.id,diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 0fb82fd3a5d6..30705ca19ffd 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -13961,6 +13961,54 @@ class TestTaskHandoffAPI(BaseTaskAPITest):},)+ # A claim left with the previous owner would refuse every rerun the new owner starts, but a replacement task the+ # previous owner still runs under the same claim keeps it.+ @parameterized.expand([("only_task_on_claim", False, "recipient"), ("replacement_shares_claim", True, "owner")])+ def test_handoff_moves_the_report_claim_the_task_works_under(+ self, _name: str, with_replacement: bool, expected_holder: str+ ) -> None:+ from products.signals.backend.facade.report_tasks import record_report_task+ from products.signals.backend.models import SignalReport++ recipient = self.create_organization_user("recipient")+ task = self.create_task(created_by=self.user)+ report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY)+ record_report_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))+ if with_replacement:+ replacement = self.create_task(title="Replacement", created_by=self.user)+ record_report_task(team_id=self.team.id, report_id=str(report.id), task_id=str(replacement.id))++ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ assignee = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/").json()["assignee"]+ holder = recipient if expected_holder == "recipient" else self.user+ self.assertEqual((assignee["kind"], assignee["user"]["id"]), ("user", holder.id))++ def test_handoff_claim_follows_the_owner_when_a_second_handoff_commits_first(self) -> None:+ from products.signals.backend.facade.report_tasks import record_report_task+ from products.signals.backend.models import SignalReport++ recipient = self.create_organization_user("recipient")+ third = self.create_organization_user("third")+ task = self.create_task(created_by=self.user)+ report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY)+ record_report_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))++ with self.captureOnCommitCallbacks() as first_handoff_callbacks:+ self.client.post(self._handoff_url(task), {"user": recipient.id}, format="json")+ recipient_client = APIClient()+ recipient_client.force_authenticate(recipient)+ with self.captureOnCommitCallbacks(execute=True):+ response = recipient_client.post(self._handoff_url(task), {"user": third.id}, format="json")+ for callback in first_handoff_callbacks:+ callback()++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ assignee = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/").json()["assignee"]+ self.assertEqual(assignee["user"]["id"], third.id)+@parameterized.expand([("active_run", False, "Finish or cancel active runs before handing off this task."),