: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): add explicit report research rerun command (#106781)
Georgiy Tarasov6a171fd7d5c1
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex 02c32b74656a..f9d5aa1f8a6c 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -21,6 +21,7 @@ from posthog.models import Team, Userfrom posthog.models.organization import OrganizationMembershipfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.oauth import McpScopePreset, grants_scratchpad_write+from posthog.user_permissions import UserPermissionsfrom products.signals.backend.agent_runtime import STEP_IMPLEMENTATION, resolve_agent_runtimefrom products.signals.backend.artefact_attribution import ArtefactAttribution@@ -80,6 +81,7 @@ from products.signals.backend.task_run_artefacts import ()from products.signals.backend.tracker_issues import create_tracker_issue_for_reportfrom products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.usage import task_run_usage_limitedlogger = structlog.get_logger(__name__)@@ -112,6 +114,19 @@ class AutostartOutcome:reason: str = ""+@frozen+class RequestedImplementation:+ team_id: int+ report_id: str+ user_id: int+ task_id: str | None+ after_run_count: int+++class RequestedImplementationUnavailable(RuntimeError):+ pass++@frozenclass ImplementationReportContent:title: str | None@@ -533,6 +548,7 @@ def _create_implementation_task_if_absent(free_trial_enabled: bool | None = None,supersede: SupersedeDecision = NO_SUPERSEDE,dispatch: ImplementationDispatch | None = None,+ requested_after_run_count: int | None = None,) -> bool:"""Create the implementation task and record it (gate row + work-log artefact), serialized per report.@@ -547,9 +563,9 @@ def _create_implementation_task_if_absent(The same lock is where billing exemptions freeze (`_stamp_billing_exemption`): the reason isdecided and written before the task exists, so it can never race a billable PR run.- ``supersede`` is the one way past the "already implemented" gate. When a research pass decides- the fix materially changed, this creates a *second* implementation task and stamps- `implemented_at_run_count` with the pass that produced it — under the same lock, so a racing+ ``supersede`` passes the "already implemented" gate when a research pass decides the fix materially changed.+ An explicit research rerun can also pass that gate after a new completed pass, for example when the selected repository changes. Both paths stamp+ `implemented_at_run_count` with the pass that produced it under the same lock, so a racingevaluation reads the stamp and declines. That stamp is what keeps one supersede decision to onereplacement pull request."""@@ -569,6 +585,12 @@ def _create_implementation_task_if_absent(return Falseif ImplementationReportContent.from_report(report) != expected_content:raise ReportChangedDuringAutostart("Report changed before its implementation task could start")+ if requested_after_run_count is not None and (+ report.status != SignalReport.Status.READY+ or report.run_count <= requested_after_run_count+ or not _has_unimplemented_work(report)+ ):+ return Falseif dispatch is not None:latest = (SignalReportArtefact.objects.filter(@@ -611,7 +633,9 @@ def _create_implementation_task_if_absent(for target in supersede.decision.targets):return False- elif claim is not None or pending_replacement(team_id, report_id) is not None:+ elif pending_replacement(team_id, report_id) is not None or (+ claim is not None and (requested_after_run_count is None or claim.actor_kind != "task")+ ):return False# The gate reads the unified task↔report view (`associated_task_runs` merges the legacy# `SignalReportTask` rows with the `task_run` artefact log). Unifying only *adds* sources,@@ -619,18 +643,24 @@ def _create_implementation_task_if_absent(# below always writes the `SignalReportTask` row, so a missing historical artefact# can't reopen the gate. Both writes happen under this lock, so a racing evaluation that# blocks here observes them and returns False.- already_implemented = bool(- SignalReport.associated_task_runs(- report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION- )+ associated_implementations = SignalReport.associated_task_runs(+ report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION)- if already_implemented and not supersede.allowed:+ already_implemented = bool(associated_implementations)+ if requested_after_run_count is not None:+ task_ids = [entry.task_id for entry in associated_implementations]+ if any(+ not run.is_terminal+ for run in tasks_facade.get_signal_report_implementation_runs(team_id, report_id, task_ids)+ ):+ return False+ if already_implemented and not supersede.allowed and requested_after_run_count is None:return Falseif already_implemented and not _has_unimplemented_work(report):# Re-checked under the lock: the caller resolved the supersede decision outside it, so a# racing evaluation that already stamped this pass must not open a second replacement.return False- if supersede.allowed and claim is not None:+ if (supersede.allowed or requested_after_run_count is not None) and claim is not None:release_claim(claim, ArtefactAttribution.system(), takeover=True)# Both stamps move together. The task about to start is built from the report as it stands# now, so neither a research pass nor a rewrite already folded into it may buy another one.@@ -707,6 +737,175 @@ def _create_implementation_task_if_absent(return True+def start_requested_implementation(request: RequestedImplementation) -> str:+ team = Team.objects.select_related("organization").get(id=request.team_id)+ user = User.objects.filter(id=request.user_id, is_active=True, organization__id=team.organization_id).first()+ if user is None or UserPermissions(user=user, team=team).current_team.effective_membership_level is None:+ raise RequestedImplementationUnavailable("The requested user cannot access the report's project")++ report = SignalReport.objects.filter(id=request.report_id, team_id=request.team_id).first()+ if report is None or report.status != SignalReport.Status.READY or report.run_count <= request.after_run_count:+ raise RequestedImplementationUnavailable("The requested research did not finish with a ready report")+ if report.implemented_at_run_count is not None and report.implemented_at_run_count >= report.run_count:+ return "already_started"+ if task_run_usage_limited(user, request.team_id):+ raise RequestedImplementationUnavailable("The requested user cannot start another task run")+ tasks_facade.enforce_self_driving_pr_quota(team, report_id=request.report_id, stage="manual_rerun")+ if pending_replacement(request.team_id, request.report_id) is not None:+ raise RequestedImplementationUnavailable("A replacement is already in progress")+ actionability_row = (+ SignalReportArtefact.objects.filter(+ team_id=request.team_id,+ report_id=request.report_id,+ type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,+ )+ .order_by("-created_at", "-id")+ .first()+ )+ actionability = (+ ActionabilityAssessment.model_validate_json(actionability_row.content) if actionability_row else None+ )+ if (+ actionability is None+ or actionability.actionability != ActionabilityChoice.IMMEDIATELY_ACTIONABLE+ or actionability.already_addressed+ ):+ raise RequestedImplementationUnavailable("The completed research is not actionable")+ repo_row = (+ SignalReportArtefact.objects.filter(+ team_id=request.team_id,+ report_id=request.report_id,+ type=SignalReportArtefact.ArtefactType.REPO_SELECTION,+ )+ .order_by("-created_at", "-id")+ .first()+ )+ repo_selection = RepoSelectionResult.model_validate_json(repo_row.content) if repo_row else None+ if repo_selection is None or repo_selection.repository is None or not report.title or not report.summary:+ raise RequestedImplementationUnavailable("The completed research has no implementation repository or summary")++ linked_tasks = {+ entry.task_id+ for entry in SignalReport.associated_task_runs(+ report_id=request.report_id,+ team_id=request.team_id,+ product=SIGNALS_PRODUCT,+ type=TASK_RUN_TYPE_IMPLEMENTATION,+ )+ }+ if request.task_id is not None and request.task_id not in linked_tasks:+ raise RequestedImplementationUnavailable("The requested task is not linked to this report")+ if request.task_id is None and len(linked_tasks) > 1:+ raise RequestedImplementationUnavailable("Choose an implementation task when the report has several")+ selected_task_id = request.task_id or next(iter(linked_tasks), None)+ selected_task = (+ tasks_facade.get_tasks_by_ids([selected_task_id], [request.team_id]) if selected_task_id is not None else []+ )+ if selected_task_id is not None and not selected_task:+ raise RequestedImplementationUnavailable("The selected implementation task is unavailable")+ if selected_task and (selected_task[0].repository or "").lower() != repo_selection.repository.lower():+ selected_task_id = None+ expected_content = ImplementationReportContent.from_report(report)++ if selected_task_id is None:+ priority_row = (+ SignalReportArtefact.objects.filter(+ team_id=request.team_id,+ report_id=request.report_id,+ type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,+ )+ .order_by("-created_at", "-id")+ .first()+ )+ priority = PriorityAssessment.model_validate_json(priority_row.content) if priority_row else None+ steering = load_report_steering(+ request.team_id, request.report_id, memory_writable=grants_scratchpad_write(IMPLEMENTATION_MCP_SCOPES)+ )+ team_config = SignalTeamConfig.objects.filter(team_id=request.team_id).first()+ created = _create_implementation_task_if_absent(+ team_id=request.team_id,+ report_id=request.report_id,+ title=report.title,+ description=_build_autostart_task_description(+ report_id=request.report_id,+ team_id=request.team_id,+ summary=report.summary,+ repository=repo_selection.repository,+ priority=priority,+ source_references=_fetch_source_references(request.team_id, request.report_id),+ steering=steering,+ ),+ expected_content=expected_content,+ user_id=request.user_id,+ repository=repo_selection.repository,+ base_branch=team_config.base_branch_for(repo_selection.repository) if team_config else None,+ steering=steering,+ free_trial_enabled=self_driving_free_trial_enabled(team),+ requested_after_run_count=request.after_run_count,+ )+ if not created:+ raise RequestedImplementationUnavailable("Another implementation started before this request")+ return "created"++ runs = tasks_facade.get_signal_report_implementation_runs(request.team_id, request.report_id, [selected_task_id])+ if not runs or not runs[0].is_terminal:+ raise RequestedImplementationUnavailable("The existing implementation task still has an active run")+ previous_run = runs[0]+ free_trial_enabled = self_driving_free_trial_enabled(team)+ with transaction.atomic():+ current = SignalReport.objects.select_for_update().get(id=request.report_id, team_id=request.team_id)+ if (+ current.status != SignalReport.Status.READY+ or ImplementationReportContent.from_report(current) != expected_content+ or pending_replacement(request.team_id, request.report_id) is not None+ or not current.title+ or not current.summary+ ):+ raise RequestedImplementationUnavailable("The report changed before implementation could start")+ if current.implemented_at_run_count is not None and current.implemented_at_run_count >= current.run_count:+ return "already_started"+ result = tasks_facade.run_task(+ selected_task_id,+ request.team_id,+ request.user_id,+ pipeline_rerun=True,+ free_trial_enabled=free_trial_enabled,+ validated_data={+ "mode": "background",+ "run_source": "signal_report",+ "resume_from_run_id": str(previous_run.id),+ "pending_user_message": (+ "The report has fresh research. Read its latest research artefacts, then reassess the existing "+ "implementation. Update the existing pull request when appropriate.\n\n"+ f"Report: {settings.SITE_URL}/project/{request.team_id}/inbox/reports/{request.report_id}\n"+ f"Title: {current.title}\n\nSummary:\n{current.summary}"+ ),+ },+ )+ if (+ result is None+ or result.error is not None+ or result.run_error+ or result.task is None+ or result.task.latest_run_id is None+ ):+ raise RequestedImplementationUnavailable("The existing implementation task could not start a new run")+ new_run = tasks_facade.get_task_run(result.task.latest_run_id, request.team_id)+ if new_run is None:+ raise RequestedImplementationUnavailable("The new implementation run could not be read")+ record_implementation_task(+ team_id=request.team_id,+ report_id=request.report_id,+ task_id=selected_task_id,+ run_id=str(new_run.id),+ automation_branch=new_run.state.get("self_driving_head_branch"),+ )+ current.implemented_at_run_count = current.run_count+ current.implemented_at_revision_count = current.content_revision_count or 0+ current.save(update_fields=["implemented_at_run_count", "implemented_at_revision_count"])+ return str(new_run.id)++def _live_skill_owner_identities(team: Team, report_id: str, reviewers_content: list[ReviewerContent], source_skill: str | None = None) -> ReviewerIdentitySet:diff --git a/products/signals/backend/management/commands/rerun_signal_report.py b/products/signals/backend/management/commands/rerun_signal_report.pynew file mode 100644index 000000000000..029ba4616a83--- /dev/null+++ b/products/signals/backend/management/commands/rerun_signal_report.py@@ -0,0 +1,198 @@+from __future__ import annotations++from datetime import timedelta+from typing import cast+from uuid import UUID++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError, CommandParser+from django.db import transaction+from django.utils import timezone++from asgiref.sync import async_to_sync+from temporalio.client import WorkflowExecutionStatus+from temporalio.common import WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.service import RPCError, RPCStatusCode++from posthog.models import User+from posthog.temporal.common.client import async_connect+from posthog.user_permissions import UserPermissions++from products.signals.backend.daily_limit import daily_report_limit_gate+from products.signals.backend.free_trial import self_driving_free_trial_enabled+from products.signals.backend.models import SignalReport+from products.signals.backend.quota import self_driving_quota_gate+from products.signals.backend.supersession import pending_replacement+from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION+from products.signals.backend.temporal.summary import SignalReportSummaryWorkflow+from products.signals.backend.temporal.types import IMPLEMENTATION_DEBOUNCE_SECONDS, SignalReportSummaryWorkflowInputs+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.usage import task_run_usage_limited+++class Command(BaseCommand):+ help = (+ "Restart research for one signal report without a running workflow, then request implementation if actionable."+ )++ researchable_statuses = frozenset(+ {+ SignalReport.Status.POTENTIAL,+ SignalReport.Status.CANDIDATE,+ SignalReport.Status.PENDING_INPUT,+ SignalReport.Status.READY,+ SignalReport.Status.RESOLVED,+ SignalReport.Status.FAILED,+ }+ )++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team-id", type=int, required=True)+ parser.add_argument("--report-id", type=UUID, required=True)+ parser.add_argument("--user-id", type=int, required=True)+ parser.add_argument("--task-id", type=UUID)+ parser.add_argument(+ "--execute", action="store_true", help="Start research. An actionable result may start a billable PR run."+ )++ async def _workflow_is_running(self, workflow_id: str) -> bool:+ client = await async_connect()+ try:+ description = await client.get_workflow_handle(workflow_id).describe()+ except RPCError as error:+ if error.status == RPCStatusCode.NOT_FOUND:+ return False+ raise+ return description.status == WorkflowExecutionStatus.RUNNING++ async def _start_workflow(self, inputs: SignalReportSummaryWorkflowInputs) -> None:+ client = await async_connect()+ await client.start_workflow(+ SignalReportSummaryWorkflow.run,+ inputs,+ id=SignalReportSummaryWorkflow.workflow_id_for(inputs.team_id, inputs.report_id),+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ execution_timeout=timedelta(hours=1, seconds=IMPLEMENTATION_DEBOUNCE_SECONDS),+ )++ def handle(self, *args: object, **options: object) -> None:+ team_id = cast(int, options["team_id"])+ report_id = str(options["report_id"])+ user_id = cast(int, options["user_id"])+ task_id = str(options["task_id"]) if options["task_id"] else None+ execute = bool(options["execute"])++ report = SignalReport.objects.select_related("team").filter(team_id=team_id, id=report_id).first()+ if report is None:+ raise CommandError("The report does not exist in the requested team")+ if report.status not in self.researchable_statuses or report.signal_count < 1:+ raise CommandError("The report must be inactive and have at least one signal")+ user = User.objects.filter(id=user_id, is_active=True, organization__id=report.team.organization_id).first()+ if user is None or UserPermissions(user=user, team=report.team).current_team.effective_membership_level is None:+ raise CommandError("The requested user cannot access the report's project")+ if task_run_usage_limited(user, team_id):+ raise CommandError("The requested user cannot start another task run")+ if pending_replacement(team_id, report_id) is not None:+ raise CommandError("An implementation replacement is already in progress")+ if self_driving_quota_gate(report.team).enforced:+ raise CommandError("The organization's self-driving credits quota blocks research")+ if daily_report_limit_gate(report.team).limited:+ raise CommandError("The project's daily report limit blocks research")+ if self_driving_free_trial_enabled(report.team):+ raise CommandError("This organization's free trial does not allow a new implementation run")+ linked_tasks = {+ entry.task_id+ for entry in SignalReport.associated_task_runs(+ report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION+ )+ }+ if task_id is not None and task_id not in linked_tasks:+ raise CommandError("The requested task is not linked to this report")+ if task_id is None and len(linked_tasks) > 1:+ raise CommandError("Select an implementation task with --task-id")+ selected_task_id = task_id or next(iter(linked_tasks), None)+ if selected_task_id is not None:+ if not tasks_facade.is_task_controllable_by_user(selected_task_id, user_id):+ raise CommandError("The requested user cannot run this implementation task")+ runs = tasks_facade.get_signal_report_implementation_runs(team_id, report_id, [selected_task_id])+ if not runs or not runs[0].is_terminal:+ raise CommandError("The implementation task has no terminal run to resume")++ workflow_id = SignalReportSummaryWorkflow.workflow_id_for(team_id, report_id)+ try:+ if async_to_sync(self._workflow_is_running)(workflow_id):+ raise CommandError(f"The report already has a running summary workflow: {workflow_id}")+ except CommandError:+ raise+ except Exception as error:+ raise CommandError(f"Could not check the summary workflow: {error}") from error++ if not execute:+ self.stdout.write(+ f"Dry run: team={team_id} report={report_id} status={report.status} run_count={report.run_count} "+ f"user={user_id} task={selected_task_id or 'new'} workflow={workflow_id}. Add --execute to start research."+ )+ return++ previous_status = report.status+ with transaction.atomic():+ report = SignalReport.objects.select_for_update().get(team_id=team_id, id=report_id)+ if report.status != previous_status or pending_replacement(team_id, report_id) is not None:+ raise CommandError("The report changed before research could start")+ previous_promoted_at = report.promoted_at+ previous_run_count = report.run_count+ update_fields = set()+ if report.status == SignalReport.Status.CANDIDATE:+ report.promoted_at = timezone.now()+ update_fields.update({"promoted_at", "updated_at"})+ elif report.status not in {SignalReport.Status.POTENTIAL, SignalReport.Status.READY}:+ update_fields.update(report.transition_to(SignalReport.Status.POTENTIAL))+ if report.status != SignalReport.Status.CANDIDATE:+ update_fields.update(report.transition_to(SignalReport.Status.CANDIDATE))+ report.save(update_fields=update_fields)+ promoted_at = report.promoted_at++ inputs = SignalReportSummaryWorkflowInputs(+ team_id=team_id,+ report_id=report_id,+ requested_implementation_user_id=user_id,+ requested_implementation_task_id=selected_task_id,+ requested_after_run_count=previous_run_count,+ )+ try:+ async_to_sync(self._start_workflow)(inputs)+ except WorkflowAlreadyStartedError as error:+ raise CommandError(f"A summary workflow already started; inspect {workflow_id} before retrying") from error+ except Exception as error:+ try:+ running = async_to_sync(self._workflow_is_running)(workflow_id)+ except Exception:+ raise CommandError(+ f"Workflow start was uncertain and the report remains candidate. Inspect {workflow_id} before retrying"+ ) from error+ if running:+ raise CommandError(f"Workflow start was uncertain, but {workflow_id} is running") from error+ restored = False+ with transaction.atomic():+ current = SignalReport.objects.select_for_update().get(team_id=team_id, id=report_id)+ if current.status == SignalReport.Status.CANDIDATE and current.promoted_at == promoted_at:+ current.status = previous_status+ current.promoted_at = previous_promoted_at+ current.save(update_fields=["status", "promoted_at"])+ restored = True+ if restored:+ raise CommandError(+ f"Could not start {workflow_id}; restored the report to {previous_status}"+ ) from error+ raise CommandError(+ f"Workflow start was uncertain and the report advanced. Inspect {workflow_id}"+ ) from error++ self.stdout.write(+ self.style.SUCCESS(+ f"Started research for report {report_id} [workflow_id={workflow_id}]. "+ "A new implementation run will start if research remains actionable."+ )+ )diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex accd7489b761..cd99a8115dec 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -28,7 +28,11 @@ from posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.artefact_attribution import ArtefactAttribution-from products.signals.backend.auto_start import maybe_autostart_from_report_artefacts+from products.signals.backend.auto_start import (+ RequestedImplementation,+ maybe_autostart_from_report_artefacts,+ start_requested_implementation,+)from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gatefrom products.signals.backend.models import SIGNALS_AT_RUN_INCREMENT, SignalReport, SignalTeamConfigfrom products.signals.backend.quota import (@@ -579,7 +583,13 @@ class SignalReportSummaryWorkflow:return Trueawait workflow.execute_activity(maybe_autostart_implementation_activity,- MaybeAutostartImplementationInput(team_id=inputs.team_id, report_id=inputs.report_id),+ MaybeAutostartImplementationInput(+ team_id=inputs.team_id,+ report_id=inputs.report_id,+ requested_user_id=inputs.requested_implementation_user_id,+ requested_task_id=inputs.requested_implementation_task_id,+ requested_after_run_count=inputs.requested_after_run_count,+ ),start_to_close_timeout=timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=3),)@@ -1014,6 +1024,9 @@ async def report_is_candidate_activity(input: ReportIsCandidateInput) -> bool:class MaybeAutostartImplementationInput:team_id: intreport_id: str+ requested_user_id: int | None = None+ requested_task_id: str | None = None+ requested_after_run_count: int | None = None@temporalio.activity.defn@@ -1024,10 +1037,23 @@ async def maybe_autostart_implementation_activity(input: MaybeAutostartImplementRuns at the workflow's settle point (report READY, no pending signals) rather than per researchrun, so the implementation task is scoped to the report's final summary — not whichever research- pass finished first. Idempotent: `maybe_autostart_from_report_artefacts` no-ops if an- implementation task already exists for the report.+ pass finished first. Normal auto-start skips an existing implementation task. An explicit+ requested rerun can start another run on that task after the new research pass."""- await maybe_autostart_from_report_artefacts(team_id=input.team_id, report_id=input.report_id)+ if input.requested_user_id is not None:+ if input.requested_after_run_count is None:+ raise ValueError("A requested implementation needs the report's prior run count")+ await database_sync_to_async(start_requested_implementation, thread_sensitive=False)(+ RequestedImplementation(+ team_id=input.team_id,+ report_id=input.report_id,+ user_id=input.requested_user_id,+ task_id=input.requested_task_id,+ after_run_count=input.requested_after_run_count,+ )+ )+ else:+ await maybe_autostart_from_report_artefacts(team_id=input.team_id, report_id=input.report_id)@dataclassdiff --git a/products/signals/backend/temporal/types.py b/products/signals/backend/temporal/types.pyindex 690fabec5fa6..405089b1c4d9 100644--- a/products/signals/backend/temporal/types.py+++ b/products/signals/backend/temporal/types.py@@ -185,7 +185,7 @@ class ReadSignalsFromS3Output:signals: list["EmitSignalInputs"]-@dataclass+@dataclass(frozen=True)class SignalReportSummaryWorkflowInputs:"""Inputs for the signal report summary workflow."""@@ -194,6 +194,9 @@ class SignalReportSummaryWorkflowInputs:# Seconds to wait before the first cycle, so a burst of signals is researched in one run rather# than one run each. Defaults to 0 so histories written before this field replay unchanged.debounce_seconds: int = 0+ requested_implementation_user_id: int | None = None+ requested_implementation_task_id: str | None = None+ requested_after_run_count: int | None = None@dataclassdiff --git a/products/signals/backend/test/test_requested_implementation.py b/products/signals/backend/test/test_requested_implementation.pynew file mode 100644index 000000000000..e90c5eddf2a2--- /dev/null+++ b/products/signals/backend/test/test_requested_implementation.py@@ -0,0 +1,252 @@+from types import SimpleNamespace++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.db import transaction++from products.signals.backend.agent_runtime import AgentRuntime+from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.auto_start import (+ NO_STEERING,+ RequestedImplementation,+ RequestedImplementationUnavailable,+ start_requested_implementation,+)+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask+from products.signals.backend.report_generation.research import ActionabilityAssessment, ActionabilityChoice+from products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.task_run_artefacts import record_implementation_task+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.models import Task, TaskRun+++class TestRequestedImplementation(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failure",+ summary="Fix the updated checkout path",+ signal_count=1,+ run_count=2,+ implemented_at_run_count=1,+ )+ self.task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ signal_report=self.report,+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ title="Implementation: Checkout failure",+ repository="example/repo",+ internal=True,+ )+ self.old_run = TaskRun.objects.create(+ team=self.team,+ task=self.task,+ status=TaskRun.Status.COMPLETED,+ environment=TaskRun.Environment.CLOUD,+ state={"ai_stage": "implementation", "self_driving_head_branch": "posthog-self-driving/checkout"},+ )+ with transaction.atomic():+ record_implementation_task(+ team_id=self.team.id,+ report_id=str(self.report.id),+ task_id=str(self.task.id),+ run_id=str(self.old_run.id),+ automation_branch="posthog-self-driving/checkout",+ )+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=str(self.report.id),+ content=ActionabilityAssessment(+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,+ already_addressed=False,+ explanation="There is a specific fix.",+ ),+ attribution=ArtefactAttribution.system(),+ )+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=str(self.report.id),+ content=RepoSelectionResult(repository="example/repo", reason="selected"),+ attribution=ArtefactAttribution.system(),+ )++ def request(self) -> RequestedImplementation:+ return RequestedImplementation(+ team_id=self.team.id,+ report_id=str(self.report.id),+ user_id=self.user.id,+ task_id=str(self.task.id),+ after_run_count=1,+ )++ def test_resumes_existing_task_once_with_fresh_research(self) -> None:+ def fake_run_task(*args: object, **kwargs: object) -> SimpleNamespace:+ new_run = TaskRun.objects.create(+ team=self.team,+ task=self.task,+ status=TaskRun.Status.NOT_STARTED,+ environment=TaskRun.Environment.CLOUD,+ state={"ai_stage": "implementation", "self_driving_head_branch": "posthog-self-driving/checkout"},+ )+ return SimpleNamespace(task=SimpleNamespace(latest_run_id=new_run.id), error=None, run_error=None)++ with (+ patch("products.signals.backend.auto_start.task_run_usage_limited", return_value=False),+ patch.object(tasks_facade, "enforce_self_driving_pr_quota"),+ patch(+ "products.signals.backend.auto_start.self_driving_free_trial_enabled", return_value=False+ ) as free_trial_flag,+ patch.object(tasks_facade, "run_task", side_effect=fake_run_task) as run_task,+ ):+ new_run_id = start_requested_implementation(self.request())+ assert start_requested_implementation(self.request()) == "already_started"++ self.report.refresh_from_db()+ assert self.report.implemented_at_run_count == 2+ assert run_task.call_count == 1+ assert run_task.call_args.kwargs["pipeline_rerun"] is True+ assert run_task.call_args.kwargs["free_trial_enabled"] is False+ free_trial_flag.assert_called_once()+ assert "Fix the updated checkout path" in run_task.call_args.kwargs["validated_data"]["pending_user_message"]+ assert SignalReportArtefact.objects.filter(+ team_id=self.team.id, report_id=self.report.id, type="task_run", content__contains=new_run_id+ ).exists()++ def test_unactionable_research_never_starts_implementation(self) -> None:+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=str(self.report.id),+ content=ActionabilityAssessment(+ actionability=ActionabilityChoice.NOT_ACTIONABLE,+ already_addressed=False,+ explanation="The evidence does not support a fix.",+ ),+ attribution=ArtefactAttribution.system(),+ )+ with (+ patch("products.signals.backend.auto_start.task_run_usage_limited", return_value=False),+ patch.object(tasks_facade, "enforce_self_driving_pr_quota"),+ patch.object(tasks_facade, "run_task") as run_task,+ ):+ try:+ start_requested_implementation(self.request())+ except RequestedImplementationUnavailable as error:+ assert "not actionable" in str(error)+ else:+ raise AssertionError("Unactionable research started implementation")+ run_task.assert_not_called()++ def test_report_without_prior_implementation_creates_a_linked_task(self) -> None:+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="New issue",+ summary="Fix the new issue",+ signal_count=1,+ run_count=1,+ )+ for content in (+ ActionabilityAssessment(+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,+ already_addressed=False,+ explanation="A code fix is needed.",+ ),+ RepoSelectionResult(repository="example/repo", reason="selected"),+ ):+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=str(report.id),+ content=content,+ attribution=ArtefactAttribution.system(),+ )++ def fake_create_and_run_task(**kwargs: object) -> SimpleNamespace:+ task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ signal_report=report,+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ title=str(kwargs["title"]),+ repository="example/repo",+ internal=True,+ )+ run = TaskRun.objects.create(team=self.team, task=task, status=TaskRun.Status.NOT_STARTED)+ return SimpleNamespace(task_id=task.id, latest_run=SimpleNamespace(id=run.id))++ with (+ patch("products.signals.backend.auto_start.task_run_usage_limited", return_value=False),+ patch.object(tasks_facade, "enforce_self_driving_pr_quota"),+ patch.object(tasks_facade, "create_and_run_task", side_effect=fake_create_and_run_task),+ patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=AgentRuntime()),+ patch("products.signals.backend.auto_start.load_report_steering", return_value=NO_STEERING),+ patch("products.signals.backend.auto_start._fetch_source_references", return_value=[]),+ patch("products.signals.backend.auto_start.self_driving_free_trial_enabled", return_value=False),+ patch("products.signals.backend.auto_start.create_tracker_issue_for_report"),+ patch("products.signals.backend.auto_start._capture_steering_attached"),+ ):+ assert (+ start_requested_implementation(+ RequestedImplementation(+ team_id=self.team.id,+ report_id=str(report.id),+ user_id=self.user.id,+ task_id=None,+ after_run_count=0,+ )+ )+ == "created"+ )++ report.refresh_from_db()+ assert report.implemented_at_run_count == 1+ assert SignalReportTask.objects.filter(+ team_id=self.team.id, report_id=report.id, relationship="implementation"+ ).exists()++ def test_repository_change_creates_a_new_task_for_the_new_research(self) -> None:+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=str(self.report.id),+ content=RepoSelectionResult(repository="example/other", reason="new evidence"),+ attribution=ArtefactAttribution.system(),+ )++ def fake_create_and_run_task(**kwargs: object) -> SimpleNamespace:+ task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ signal_report=self.report,+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ title=str(kwargs["title"]),+ repository="example/other",+ internal=True,+ )+ run = TaskRun.objects.create(team=self.team, task=task, status=TaskRun.Status.NOT_STARTED)+ return SimpleNamespace(task_id=task.id, latest_run=SimpleNamespace(id=run.id))++ with (+ patch("products.signals.backend.auto_start.task_run_usage_limited", return_value=False),+ patch.object(tasks_facade, "enforce_self_driving_pr_quota"),+ patch.object(tasks_facade, "create_and_run_task", side_effect=fake_create_and_run_task),+ patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=AgentRuntime()),+ patch("products.signals.backend.auto_start.load_report_steering", return_value=NO_STEERING),+ patch("products.signals.backend.auto_start._fetch_source_references", return_value=[]),+ patch("products.signals.backend.auto_start.self_driving_free_trial_enabled", return_value=False),+ patch("products.signals.backend.auto_start.create_tracker_issue_for_report"),+ patch("products.signals.backend.auto_start._capture_steering_attached"),+ ):+ assert start_requested_implementation(self.request()) == "created"++ self.report.refresh_from_db()+ assert self.report.implemented_at_run_count == 2+ assert (+ SignalReportTask.objects.filter(+ team_id=self.team.id, report_id=self.report.id, relationship="implementation"+ ).count()+ == 2+ )+ assert Task.objects.filter(team=self.team, signal_report=self.report, repository="example/other").exists()diff --git a/products/signals/backend/test/test_rerun_signal_report_command.py b/products/signals/backend/test/test_rerun_signal_report_command.pynew file mode 100644index 000000000000..86f68f668070--- /dev/null+++ b/products/signals/backend/test/test_rerun_signal_report_command.py@@ -0,0 +1,155 @@+from datetime import timedelta+from io import StringIO+from types import SimpleNamespace++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, patch++from django.core.management import call_command+from django.core.management.base import CommandError+from django.utils import timezone++from parameterized import parameterized++from products.signals.backend.management.commands.rerun_signal_report import Command+from products.signals.backend.models import SignalReport+++class TestRerunSignalReportCommand(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failure",+ summary="Fix the checkout path",+ signal_count=1,+ run_count=2,+ )+ quota_patch = patch(+ "products.signals.backend.management.commands.rerun_signal_report.self_driving_quota_gate",+ return_value=SimpleNamespace(enforced=False),+ )+ quota_patch.start()+ self.addCleanup(quota_patch.stop)+ daily_limit_patch = patch(+ "products.signals.backend.management.commands.rerun_signal_report.daily_report_limit_gate",+ return_value=SimpleNamespace(limited=False),+ )+ daily_limit_patch.start()+ self.addCleanup(daily_limit_patch.stop)+ usage_patch = patch(+ "products.signals.backend.management.commands.rerun_signal_report.task_run_usage_limited",+ return_value=False,+ )+ usage_patch.start()+ self.addCleanup(usage_patch.stop)+ trial_patch = patch(+ "products.signals.backend.management.commands.rerun_signal_report.self_driving_free_trial_enabled",+ return_value=False,+ )+ trial_patch.start()+ self.addCleanup(trial_patch.stop)++ def command(self, *, execute: bool = False) -> str:+ output = StringIO()+ call_command(+ "rerun_signal_report",+ team_id=self.team.id,+ report_id=self.report.id,+ user_id=self.user.id,+ execute=execute,+ stdout=output,+ )+ return output.getvalue()++ @patch.object(Command, "_start_workflow", new_callable=AsyncMock)+ @patch.object(Command, "_workflow_is_running", new_callable=AsyncMock, return_value=False)+ def test_dry_run_does_not_promote_or_start(self, _running: AsyncMock, start: AsyncMock) -> None:+ assert "Dry run" in self.command()+ self.report.refresh_from_db()+ assert self.report.status == SignalReport.Status.READY+ start.assert_not_awaited()++ @parameterized.expand(+ [+ ("ready", SignalReport.Status.READY),+ ("candidate", SignalReport.Status.CANDIDATE),+ ("failed", SignalReport.Status.FAILED),+ ("pending_input", SignalReport.Status.PENDING_INPUT),+ ("resolved", SignalReport.Status.RESOLVED),+ ("potential", SignalReport.Status.POTENTIAL),+ ]+ )+ @patch.object(Command, "_start_workflow", new_callable=AsyncMock)+ @patch.object(Command, "_workflow_is_running", new_callable=AsyncMock, return_value=False)+ def test_execute_starts_fresh_research_with_implementation_request(+ self, _name: str, status: SignalReport.Status, _running: AsyncMock, start: AsyncMock+ ) -> None:+ self.report.status = status+ self.report.save(update_fields=["status"])+ previous_promoted_at = self.report.promoted_at+ assert "Started research" in self.command(execute=True)+ self.report.refresh_from_db()+ assert self.report.status == SignalReport.Status.CANDIDATE+ if status == SignalReport.Status.CANDIDATE:+ assert self.report.promoted_at != previous_promoted_at+ start.assert_awaited_once()+ assert start.await_args is not None+ inputs = start.await_args.args[0]+ assert inputs.report_id == str(self.report.id)+ assert inputs.requested_implementation_user_id == self.user.id+ assert inputs.requested_after_run_count == 2++ @patch.object(Command, "_workflow_is_running", new_callable=AsyncMock, return_value=True)+ def test_running_summary_workflow_blocks_restart(self, _running: AsyncMock) -> None:+ try:+ self.command(execute=True)+ except CommandError as error:+ assert "already has a running summary workflow" in str(error)+ else:+ raise AssertionError("The command started alongside an active summary workflow")+ self.report.refresh_from_db()+ assert self.report.status == SignalReport.Status.READY++ @patch.object(Command, "_start_workflow", new_callable=AsyncMock)+ @patch(+ "products.signals.backend.management.commands.rerun_signal_report.daily_report_limit_gate",+ return_value=SimpleNamespace(limited=True),+ )+ def test_daily_limit_blocks_before_report_promotion(self, _limit: object, start: AsyncMock) -> None:+ try:+ self.command(execute=True)+ except CommandError as error:+ assert "daily report limit blocks research" in str(error)+ else:+ raise AssertionError("A limited team started research")+ self.report.refresh_from_db()+ assert self.report.status == SignalReport.Status.READY+ start.assert_not_awaited()++ @parameterized.expand(+ [+ ("ready", SignalReport.Status.READY),+ ("failed", SignalReport.Status.FAILED),+ ("candidate", SignalReport.Status.CANDIDATE),+ ]+ )+ @patch.object(Command, "_start_workflow", new_callable=AsyncMock, side_effect=RuntimeError("start failed"))+ @patch.object(Command, "_workflow_is_running", new_callable=AsyncMock, return_value=False)+ def test_failed_workflow_start_restores_original_status(+ self, _name: str, status: SignalReport.Status, _running: AsyncMock, _start: AsyncMock+ ) -> None:+ self.report.status = status+ self.report.promoted_at = timezone.now() - timedelta(minutes=1)+ self.report.save(update_fields=["status", "promoted_at"])+ original_promoted_at = self.report.promoted_at+ try:+ self.command(execute=True)+ except CommandError as error:+ assert f"restored the report to {status}" in str(error)+ else:+ raise AssertionError("A failed workflow start appeared successful")+ self.report.refresh_from_db()+ assert self.report.status == status+ assert self.report.promoted_at == original_promoted_atdiff --git a/products/signals/backend/test/test_summary_settle_autostart.py b/products/signals/backend/test/test_summary_settle_autostart.pyindex ef696c5c9402..3aab69f663fc 100644--- a/products/signals/backend/test/test_summary_settle_autostart.py+++ b/products/signals/backend/test/test_summary_settle_autostart.py@@ -129,6 +129,7 @@ class _Recorder:# child only waits for the implementation PR if the task already exists then, so a 0 here# means the card ships without the PR link.self.autostarts_at_notification: list[int] = []+ self.autostart_inputs: list[MaybeAutostartImplementationInput] = []def _signal_data() -> SignalData:@@ -157,7 +158,9 @@ class _StubInboxNotificationWorkflow:)-async def _run_summary_workflow(recorder: _Recorder) -> None:+async def _run_summary_workflow(+ recorder: _Recorder, *, requested_user_id: int | None = None, requested_after_run_count: int | None = None+) -> None:@activity.defn(name="check_report_quota_gate_activity")async def fake_quota(input) -> bool:return False@@ -212,6 +215,7 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:@activity.defn(name="maybe_autostart_implementation_activity")async def fake_autostart(input: MaybeAutostartImplementationInput) -> None:recorder.autostarts += 1+ recorder.autostart_inputs.append(input)@activity.defn(name="record_notification_check_activity")async def fake_notification_check(input: InboxNotificationInput) -> None:@@ -243,7 +247,12 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:await asyncio.wait_for(env.client.execute_workflow(SignalReportSummaryWorkflow.run,- SignalReportSummaryWorkflowInputs(team_id=1, report_id=report_id),+ SignalReportSummaryWorkflowInputs(+ team_id=1,+ report_id=report_id,+ requested_implementation_user_id=requested_user_id,+ requested_after_run_count=requested_after_run_count,+ ),id=f"summary-settle-{uuid.uuid4()}",task_queue=TASK_QUEUE,),@@ -271,6 +280,16 @@ async def test_no_buffer_autostarts_immediately_at_settle():assert recorder.autostarts_at_notification == [1]+async def test_requested_implementation_reaches_settle_after_fresh_research():+ recorder = _Recorder(buffer_seconds=0, candidate_on_first_check=False)+ await _run_summary_workflow(recorder, requested_user_id=42, requested_after_run_count=5)+ assert recorder.researches == 1+ assert len(recorder.autostart_inputs) == 1+ assert recorder.autostart_inputs[0].requested_user_id == 42+ assert recorder.autostart_inputs[0].requested_after_run_count == 5++@pytest.mark.asyncioasync def test_buffer_autostarts_when_no_signal_arrives():recorder = _Recorder(buffer_seconds=120, candidate_on_first_check=False)diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 46ff3140af80..d2e7dab224dd 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -8081,6 +8081,8 @@ def run_task(*,validated_data: dict,warm_retry_token: str | None = None,+ pipeline_rerun: bool = False,+ free_trial_enabled: bool | None = None,) -> contracts.TaskRunResult | None:"""Create a run for a task and kick off its workflow, mirroring ``TaskViewSet.run``.@@ -8088,6 +8090,8 @@ def run_task(``TaskRunResult`` carrying the refreshed task detail DTO or a structured error. The usagegate (429) is applied by the view before calling this. A report implementation raises``FreeTrialPullRequestRefused`` (402) while the team's org is on a self-driving free trial.+ ``pipeline_rerun`` is reserved for a server-requested Signals research rerun. It creates a+ fresh run and stamps the protected implementation stage from the verified report-task link."""from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product read kept off the api import pathenforce_report_implementation_rerun_cap,@@ -8127,17 +8131,22 @@ def run_task(if task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORTelse None)+ is_implementation = Falseif report_id_for_slot_check is not None:# Free trial gate: the create-time gate refuses a new implementation, but a task created# before sales turned the flag on can still be started or retried from here, and its pull# request bills the trial org. Only the implementation relationship opens one, so a# discussion keeps running. Outside the transaction below, because the flag read does# network I/O and must not hold the report row lock.- if is_report_implementation_task(team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)):+ is_implementation = is_report_implementation_task(+ team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)+ )+ if is_implementation:enforce_self_driving_free_trial(Team.objects.select_related("organization").get(id=team_id),report_id=report_id_for_slot_check,stage="task_run",+ enabled=free_trial_enabled,)# Ahead of the warm-run reuse below, which returns early: a task released its slot when# its runs all failed, so another implementation may hold it by now. Refusing here also@@ -8230,7 +8239,11 @@ def run_task(attr="codex_model_access" if codex_model_access == "own-subscription" else "claude_model_access",))- warm_run = None if scheduled_at is not None or run_source == RunSource.AGENT else _idling_warm_run_for_task(task)+ warm_run = (+ None+ if pipeline_rerun or scheduled_at is not None or run_source == RunSource.AGENT+ else _idling_warm_run_for_task(task)+ )# A warm sandbox was started before the plan choice, so it holds no run-scoped subscription token.if warm_run is not None and model_access.kind == "own-subscription":warm_run = None@@ -8396,6 +8409,8 @@ def run_task(prev_self_driving_head_branch = (previous_run.state or {}).get("self_driving_head_branch")if prev_self_driving_head_branch:extra_state["self_driving_head_branch"] = prev_self_driving_head_branch+ if pipeline_rerun and task.internal and is_implementation:+ extra_state["ai_stage"] = "implementation"# A read-only GitHub grant describes how the task was created, not one run — without the# carry-forward, a resumed successor of a repo-less read-only run falls through to thediff --git a/products/tasks/backend/facade/usage.py b/products/tasks/backend/facade/usage.pynew file mode 100644index 000000000000..09f32ec550c3--- /dev/null+++ b/products/tasks/backend/facade/usage.py@@ -0,0 +1,12 @@+from __future__ import annotations++from typing import TYPE_CHECKING++from products.tasks.backend.logic.services.code_usage_gate import usage_limit_response++if TYPE_CHECKING:+ from posthog.models import User+++def task_run_usage_limited(user: User, team_id: int) -> bool:+ return usage_limit_response(user, team_id) is not Nonediff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex b91a50754f81..11fcdf7c3e16 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -1204,19 +1204,34 @@ class TestFacadeReadsAndMappers(TestCase):new_run = task.runs.exclude(id=previous_run.id).get()self.assertEqual(new_run.state.get("self_driving_head_branch"), "posthog-self-driving/fix-abc123")- def test_run_task_resume_of_a_pipeline_task_stays_unstamped(self):- # The predecessor's stage is deliberately not carried forward: a stage makes the run- # read as pipeline-started and drops it out of the interactive duration ceiling.+ @parameterized.expand(+ [+ ("manual_implementation", False, "implementation", "implementation", None),+ ("pipeline_after_manual", True, "implementation", None, "implementation"),+ ("pipeline_discussion", True, "discussion", "implementation", None),+ ]+ )+ def test_run_task_resume_of_a_pipeline_task_stamps_only_requested_pipeline_runs(+ self,+ _name: str,+ pipeline_rerun: bool,+ relationship: str,+ previous_stage: str | None,+ expected_stage: str | None,+ ):from products.signals.backend.models import SignalReport+ from products.signals.backend.task_run_artefacts import record_report_task- # The report link is present so only `internal` can withhold the stamp here.report = SignalReport.objects.create(team=self.team)task = self._make_task(origin_product=Task.OriginProduct.SIGNAL_REPORT, signal_report=report, internal=True)+ record_report_task(+ team_id=self.team.id, report_id=str(report.id), task_id=str(task.id), relationship=relationship+ )previous_run = TaskRun.objects.create(task=task,team=self.team,status=TaskRun.Status.COMPLETED,- state={"ai_stage": "implementation"},+ state={"ai_stage": previous_stage} if previous_stage else {},)with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):@@ -1225,11 +1240,13 @@ class TestFacadeReadsAndMappers(TestCase):self.team.id,self.user.id,validated_data={"mode": "interactive", "resume_from_run_id": str(previous_run.id)},+ pipeline_rerun=pipeline_rerun,+ free_trial_enabled=False,)assert result is not None and result.error is Nonenew_run = task.runs.exclude(id=previous_run.id).get()- self.assertNotIn("ai_stage", new_run.state)+ self.assertEqual(new_run.state.get("ai_stage"), expected_stage)@parameterized.expand([@@ -2516,3 +2533,34 @@ class TestSelfDrivingFreeTrialFacadeGates(TestCase):)flag_mock.assert_not_called()self.assertTrue(Task.objects.filter(id=dto.task_id).exists())++ def test_run_task_takes_a_pre_resolved_free_trial_verdict(self):+ from products.signals.backend.task_run_artefacts import record_report_task++ report = self._report()+ task = Task.objects.create(+ team=self.team,+ title="Implementation: t",+ description="d",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report_id=report.id,+ created_by=self.user,+ )+ record_report_task(+ team_id=self.team.id, report_id=str(report.id), task_id=str(task.id), relationship="implementation"+ )++ with (+ self._on_trial() as flag_mock,+ patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None),+ ):+ result = facade.run_task(+ task.id,+ self.team.id,+ self.user.id,+ validated_data={"mode": "background"},+ free_trial_enabled=False,+ )+ flag_mock.assert_not_called()+ assert result is not None and result.error is None+ self.assertTrue(task.runs.exists())