: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): hold back pull requests for orgs on a self-driving free trial (#98128)
Alex Lebedev45439194e05f
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 83fc4e476d42..c42804b970d5 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -224,6 +224,7 @@ export const FEATURE_FLAGS = {REPLAY_SETTINGS_HELP: 'replay-settings-help', // owner: @veryayskiy #team-replaySCOUTS_MODEL_CONFIG: 'scouts-model-config', // owner: #team-self-driving, gates the per-scout model pin in the inbox scout settings (also checked server-side)SCOUTS_SUGGESTIONS_UI: 'scouts-suggestions-ui', // owner: #team-self-driving, gates the pre-computed scout suggestions strip on the inbox scouts tab (the producer is the separate signals-scout-suggestions flag)+ SELF_DRIVING_FREE_TRIAL: 'self-driving-free-trial', // owner: #team-self-driving, the org is on a Self-driving free trial: reports only, no pull requests (also checked server-side)SELF_DRIVING_QUOTA_ENFORCEMENT: 'self-driving-quota-enforcement', // owner: #team-self-driving, gates self-driving PR-limit enforcement (also checked server-side)SESSION_REPLAY_BACKEND_LOGS: 'session-replay-backend-logs', // owner: #team-replaySESSION_REPLAY_DOCTOR: 'session-replay-doctor', // owner: #team-replaydiff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 46624464b6f8..102d3e8c578a 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1018,6 +1018,7 @@ All events use `distinct_id = team.uuid` and `groups(organization, team)`. Per-s- `signal_report_reresearch_skipped` — signal hit an already-researched report past the re-research cap, so no new run spawned (+ `report_id`, `signal_count`, `status`, `threshold`). Fires per suppressed signal- `signal_report_quota_paused` — a quota gate observed the team's org over its self-driving credits limit (+ `stage`: `promotion` | `summary_entry` | `pre_repo_selection` | `pre_research` | `autostart` | `manual_create` | `task_create` | `implementation_run`, `enforced`, `report_id`). See Billing limit enforcement- `signal_report_daily_limit_paused` — a gate paused work because the team hit its `max_reports_per_day` (+ `stage`: `ingestion` | `scout_run` | `promotion` | `summary_entry` | `pre_repo_selection` | `pre_research`, `limit`, `reports_today`, `report_id` nullable). See Per-team daily report limit+- `signal_report_free_trial_paused` — a gate held back a pull request because the team's org is on a Self-driving free trial (+ `stage`: `autostart` | `manual_create` | `task_create` | `task_run`, `report_id` nullable). See Self-driving free trial- `signal_report_started` — report run began (+ `report_id`, `signal_count`, `run_count`, `source_products`)- `signals_repo_research_started` / `signals_repo_research_completed` — repo selection stage (+ `report_id`, `result`: `reused` | `selected` | `no_repo` | `failed`, optional `failure_reason`: `no_github_integration` | `agentic_activity_error`)- `signal_report_completed` — terminal per run (+ `result`: `ready` | `failed` | `pending_input` | `not_actionable`, optional `failure_reason`)@@ -1163,6 +1164,7 @@ Runs inside `maybe_autostart_implementation_task()` in `backend/auto_start.py`,- Report has a `priority_judgment`- Report has suggested reviewers- No legacy `SignalReportTask` implementation row exists for the report (checked inside a `select_for_update` on the report row, so concurrent evaluations can't double-start)+- The team's org is not on a Self-driving free trial, and not over its self-driving credits quota with enforcement on (see Billing limit enforcement)**User selection** via `_resolve_autostart_assignee()` in `backend/auto_start.py`:@@ -1353,6 +1355,27 @@ No `enforced` property: every event is a real block.Unlike the billing gates, the ingestion and scout stages do emit (with `report_id=null`) — the limit is user-set and the volume is bounded by the team's own signal flow, and the events answer "why did nothing arrive today".Promotion-stage events keep the billing discipline of firing only when the signal would have promoted; both events fire independently when both limits bind.+### Self-driving free trial++A third pause with the same shape, on the implementation side only: while the `self-driving-free-trial` flag is on for an org (org-keyed, toggled by sales per trial), Self-driving still researches and writes reports but opens no pull requests.+Billing happens only when a PR opens, so nothing is billed, and the exemption and refund machinery in `billing.py` is not involved.+Implemented in `backend/free_trial.py`, a sibling of `quota.py` with the same fail-open posture: a flag-read error counts as "not on trial", because a flag outage must not stop every org's PRs.++| Stage | Where | Behavior on a trial |+| ------------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `autostart` | `maybe_autostart_implementation_task` (all callers) | No implementation task is created; the report stays ready |+| `manual_create` / `task_create` | tasks facade `create_task` / `create_and_run_task` | An implementation task from a report is refused with 402, code `self_driving_free_trial` (`FreeTrialPullRequestRefused`); a `discussion` task from a report is allowed |+| `task_run` | tasks facade `run_task` | Starting or retrying an implementation task that already existed is refused the same way; a `discussion` task keeps running |++The research-side gates are not involved: a trial org is meant to get every report.+The block is blanket, so billing-exempt reports (health checks) are held back too.+Discuss stays open: a Discuss run can still open a PR, and billing never counts it, because billing only counts implementation records. That is an accepted risk of a sales trial.+The inbox reads the same flag and keeps Create PR visible but disabled (detail pane, triage view, card context menu) with the sentence the refusal carries (`FREE_TRIAL_PR_MESSAGE`); the desktop app gets the server refusal only.+A run that is already in flight when the flag goes on is not stopped, because there is no mid-run check like the quota gate's; it can still open its PR.+Resume is organic, like the other pauses: nothing restarts when the flag goes off; a held-back report gets its PR on the next auto-start re-evaluation, or by hand.++**Telemetry:** each gate emits `signal_report_free_trial_paused` with `stage` (`autostart` | `manual_create` | `task_create` | `task_run`), `report_id`, `team_id`, and `organization_id`. Every event is a real block.+---## Data Types (`backend/temporal/types.py`)diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex d0e599ce9eac..eeb498a9391f 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -24,6 +24,7 @@ from products.signals.backend.billing import (mark_report_billing_exempt,system_billing_exempt_reason,)+from products.signals.backend.free_trial import capture_signal_report_free_trial_paused, self_driving_free_trial_enabledfrom products.signals.backend.models import (SignalReport,SignalReportArtefact,@@ -385,6 +386,7 @@ def _create_implementation_task_if_absent(base_branch: str | None,billing_exempt_reason: str | None = None,steering: ReportSteering = NO_STEERING,+ free_trial_enabled: bool | None = None,) -> bool:"""Create the implementation task and record it (gate row + work-log artefact), serialized per report.@@ -434,6 +436,9 @@ def _create_implementation_task_if_absent(repository=repository,branch=base_branch,signal_report_id=report_id,+ # Resolved by the caller outside this lock, like `agent_runtime` above, so the+ # create-time free-trial gate makes no flag request while the report row is locked.+ free_trial_enabled=free_trial_enabled,# `full` scopes so the implementation agent can log its work on the report (notes,# code references) via the task:write artefact tools, plus the scratchpad so what it# learned about the codebase outlives the run.@@ -816,6 +821,21 @@ async def maybe_autostart_implementation_task()return+ # Free trial gate: a trial org gets reports, not pull requests, so no implementation task on+ # any path. The report stays ready and gets its PR after the trial, on the next re-evaluation+ # or by hand. The gate sits after the runner resolution because a report with no runner opens+ # no pull request anyway, so counting it would overstate what the trial held back.+ on_free_trial = await database_sync_to_async(self_driving_free_trial_enabled, thread_sensitive=False)(team)+ if on_free_trial:+ capture_signal_report_free_trial_paused(team, report_id=report_id, stage="autostart")+ logger.info(+ "self-driving auto-start skipped",+ report_id=report_id,+ team_id=team_id,+ reason="org on self-driving free trial",+ )+ return+base_branch = team_config.base_branch_for(repository) if team_config else Nonesource_references = await database_sync_to_async(_fetch_source_references, thread_sensitive=False)(@@ -843,6 +863,9 @@ async def maybe_autostart_implementation_task(base_branch=base_branch,billing_exempt_reason=billing_exempt_reason,steering=steering,+ # The verdict resolved above, so the create-time gate re-reads no flag while it holds the+ # report row lock.+ free_trial_enabled=on_free_trial,)if not created:# Another evaluation won the race and already created the implementation task.diff --git a/products/signals/backend/free_trial.py b/products/signals/backend/free_trial.pynew file mode 100644index 000000000000..65aca8bc5969--- /dev/null+++ b/products/signals/backend/free_trial.py@@ -0,0 +1,86 @@+"""Self-driving free trial gate.++Sibling of `quota.py` (the org-level billing quota gate) with the same call shape and the same+fail-open posture. While the `self-driving-free-trial` flag is on for an org, Self-driving still+researches and writes reports but opens no pull requests: auto-start creates no implementation+task and the manual create-from-report path refuses one. Nothing is billed because nothing ships+a PR, so the billing exemption and refund machinery in `billing.py` stays untouched.+"""++from typing import TYPE_CHECKING++import structlog+import posthoganalytics+from rest_framework import status+from rest_framework.exceptions import APIException++from posthog.event_usage import groups++if TYPE_CHECKING:+ from posthog.models import Team++logger = structlog.get_logger(__name__)++# Org-keyed; sales toggles it per trial.+SELF_DRIVING_FREE_TRIAL_FLAG = "self-driving-free-trial"++# Shown wherever a trial org asks for a pull request: the disabled Create PR button and the+# refused create-from-report call. One sentence, so it reads the same on every surface.+FREE_TRIAL_PR_MESSAGE = (+ "During your free trial, Self-driving writes reports but doesn't open pull requests. Contact us to upgrade."+)+++class FreeTrialPullRequestRefused(APIException):+ """A trial org asked for a pull request. 402 like the quota gate, with its own code so clients+ can tell the trial apart from a spend limit."""++ status_code = status.HTTP_402_PAYMENT_REQUIRED+ default_code = "self_driving_free_trial"+ default_detail = FREE_TRIAL_PR_MESSAGE+++def self_driving_free_trial_enabled(team: "Team") -> bool:+ """Whether the team's org is on a Self-driving free trial.++ Org-keyed like the quota-enforcement and refund flags. Fails open (not on trial) on a+ flag-read error: a flag outage must not stop every org's pull requests. Blocking network+ I/O; wrap in `sync_to_async` from async code.+ """+ try:+ org_id = str(team.organization_id)+ return (+ posthoganalytics.feature_enabled(+ SELF_DRIVING_FREE_TRIAL_FLAG,+ org_id,+ groups={"organization": org_id},+ group_properties={"organization": {"id": org_id}},+ )+ is True+ )+ except Exception:+ logger.warning("self_driving_free_trial_flag_check_failed", exc_info=True)+ return False+++def capture_signal_report_free_trial_paused(team: "Team", *, report_id: str | None, stage: str) -> None:+ """`signal_report_free_trial_paused`: a gate held back a pull request at `stage` because the+ team's org is on a free trial. Every event is a real block. Best-effort: telemetry must never+ fail the step that emitted it. Requires `team.organization` to be loaded.+ """+ try:+ posthoganalytics.capture(+ event="signal_report_free_trial_paused",+ distinct_id=str(team.uuid),+ properties={+ "team_id": team.id,+ "organization_id": str(team.organization_id),+ "report_id": report_id,+ "stage": stage,+ },+ groups=groups(team.organization, team),+ )+ except Exception:+ logger.exception(+ "Failed to capture signal_report_free_trial_paused", report_id=report_id, team_id=team.id, stage=stage+ )diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.pyindex 043b360850dd..e2387d8d7570 100644--- a/products/signals/backend/task_run_artefacts.py+++ b/products/signals/backend/task_run_artefacts.py@@ -48,6 +48,7 @@ __all__ = ["append_task_run_artefact","enforce_report_implementation_rerun_cap","enforce_report_task_cap",+ "is_report_implementation_task","record_implementation_task","record_report_task","release_quota_cancelled_implementation",@@ -254,6 +255,17 @@ def enforce_report_task_cap(*, team_id: int, report_id: str, relationship: str |)+def is_report_implementation_task(*, team_id: int, report_id: str, task_id: str) -> bool:+ """Whether this task is the report's implementation, the relationship that opens a pull request.++ Reads the `SignalReportTask` gate rows rather than the artefact log, because the log is+ API-mutable and so cannot carry a spend-controlling decision.+ """+ return SignalReportTask.objects.filter(+ team_id=team_id, report_id=report_id, task_id=task_id, relationship=TASK_RUN_TYPE_IMPLEMENTATION+ ).exists()++def enforce_report_implementation_rerun_cap(*, team_id: int, report_id: str, task_id: str) -> None:"""Re-check the one-live-implementation slot before starting another run of an existing task.@@ -278,10 +290,7 @@ def enforce_report_implementation_rerun_cap(*, team_id: int, report_id: str, tasraise RuntimeError("enforce_report_implementation_rerun_cap must run inside a transaction; it locks the report row")- is_implementation = SignalReportTask.objects.filter(- team_id=team_id, report_id=report_id, task_id=task_id, relationship=TASK_RUN_TYPE_IMPLEMENTATION- ).exists()- if not is_implementation:+ if not is_report_implementation_task(team_id=team_id, report_id=report_id, task_id=task_id):returnreport = SignalReport.objects.select_for_update().filter(id=report_id, team_id=team_id).first()if report is None:diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.pyindex cd9f7071e083..63ccc5c7d2b8 100644--- a/products/signals/backend/test/test_auto_start.py+++ b/products/signals/backend/test/test_auto_start.py@@ -906,6 +906,83 @@ async def test_quota_gate_blocks_autostart_only_when_enforced(enforced):assert (mock_create.call_count == 0) is enforced[email protected]_db(transaction=True)+ ("on_trial", "repository_autostart_eligible", "expect_task", "expect_pause_event"),+ [+ (True, True, False, True),+ (False, True, True, False),+ # An inferred repository blocks the reviewer-less fallback, so no runner resolves and the+ # report opens no pull request off the trial either. The trial held nothing back, so the+ # sales count must not carry it.+ (True, False, False, False),+ ],+)+async def test_free_trial_gate_blocks_autostart(+ on_trial, repository_autostart_eligible, expect_task, expect_pause_event+):+ # A trial org gets reports, not pull requests: the implementation task is the step that opens+ # one, so auto-start creates none while the flag is on, and counts the held-back PR.+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")++ def _setup() -> tuple[Team, SignalReport]:+ organization = Organization.objects.create(name="trial-org")+ team = Team.objects.create(organization=organization, name="trial-team")+ enabler = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(user=enabler, organization=organization)+ SignalSourceConfig.objects.create(+ team=team, source_product="error_tracking", source_type="issue_created", created_by=enabler+ )+ report = SignalReport.objects.create(+ team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0+ )+ return team, report++ team, report = await sync_to_async(_setup)()++ def _fake_create_and_run_task(**kwargs):+ task = Task.objects.create(+ team_id=team.id,+ title=kwargs["title"],+ description=kwargs["description"],+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )+ run = TaskRun.objects.create(task=task, team_id=team.id)+ return SimpleNamespace(task_id=task.id, team_id=team.id, latest_run=SimpleNamespace(id=run.id))++ with (+ patch.object(tasks_facade, "create_and_run_task", side_effect=_fake_create_and_run_task) as mock_create,+ patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=AgentRuntime()),+ patch("products.signals.backend.auto_start.self_driving_free_trial_enabled", return_value=on_trial),+ patch("products.signals.backend.auto_start.capture_signal_report_free_trial_paused") as capture_mock,+ ):+ await maybe_autostart_implementation_task(+ team_id=team.id,+ report_id=str(report.id),+ repository="owner/repo",+ title="t",+ summary="s",+ actionability=ActionabilityAssessment(+ explanation="Clear fix in the affected module.",+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,+ already_addressed=False,+ ),+ reviewers_content=[],+ priority=PriorityAssessment(explanation="Affects many sessions.", priority=Priority.P2),+ repository_autostart_eligible=repository_autostart_eligible,+ )++ assert (mock_create.call_count == 1) is expect_task+ if expect_task:+ # The verdict travels with the create, so the gate behind it re-reads no flag under the lock.+ assert mock_create.call_args.kwargs["free_trial_enabled"] is False+ assert (capture_mock.call_count == 1) is expect_pause_event+ if expect_pause_event:+ assert capture_mock.call_args.kwargs == {"report_id": str(report.id), "stage": "autostart"}++@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize("autostart_eligible", [True, False])diff --git a/products/signals/backend/test/test_free_trial.py b/products/signals/backend/test/test_free_trial.pynew file mode 100644index 000000000000..b5df229ccb6d--- /dev/null+++ b/products/signals/backend/test/test_free_trial.py@@ -0,0 +1,33 @@+import pytest+from unittest.mock import patch++from posthog.models import Organization, Team++from products.signals.backend.free_trial import SELF_DRIVING_FREE_TRIAL_FLAG, self_driving_free_trial_enabled+++ "flag_result,expected",+ [+ (True, True),+ (False, False),+ (None, False),+ (RuntimeError("flag service down"), False),+ ],+)+def test_self_driving_free_trial_enabled_reads_the_org_flag_and_fails_open(flag_result, expected):+ organization = Organization.objects.create(name="trial-org")+ team = Team.objects.create(organization=organization, name="trial-team")+ kwargs = {"side_effect": flag_result} if isinstance(flag_result, Exception) else {"return_value": flag_result}++ with patch("products.signals.backend.free_trial.posthoganalytics.feature_enabled", **kwargs) as feature_enabled:+ assert self_driving_free_trial_enabled(team) is expected++ org_id = str(organization.id)+ feature_enabled.assert_called_once_with(+ SELF_DRIVING_FREE_TRIAL_FLAG,+ org_id,+ groups={"organization": org_id},+ group_properties={"organization": {"id": org_id}},+ )diff --git a/products/signals/frontend/inbox/components/cards/ReportContextMenu.tsx b/products/signals/frontend/inbox/components/cards/ReportContextMenu.tsxindex 50b94eb086c0..636bc2367805 100644--- a/products/signals/frontend/inbox/components/cards/ReportContextMenu.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportContextMenu.tsx@@ -1,4 +1,4 @@-import { useActions } from 'kea'+import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { ReactNode, useRef } from 'react'@@ -129,6 +129,7 @@ function ReportContextMenuItems({// Kept mounted by `ReportsTab` beyond this menu's lifetime, so the create-PR listener survives// the menu closing on click.const { createPrFromReport } = useActions(inboxTaskKickoffLogic)+ const { createPrDisabledReason } = useValues(inboxTaskKickoffLogic)const reportTitle = displayConventionalCommitTitle(report.title, 'Untitled report')const hasOpenPr = hasOpenImplementationPr(report)@@ -272,10 +273,13 @@ function ReportContextMenuItems({<ContextMenuGroup>{canCreateImplementationPr(report) && (<>- <ContextMenuItem asChild>+ <ContextMenuItem asChild disabled={!!createPrDisabledReason}><ButtonPrimitivemenuItemonClick={onCreatePr}+ disabledReasons={+ createPrDisabledReason ? { [createPrDisabledReason]: true } : undefined+ }data-attr="inbox-report-context-menu-create-pr"><IconPullRequest />diff --git a/products/signals/frontend/inbox/components/detail/CreatePrButton.tsx b/products/signals/frontend/inbox/components/detail/CreatePrButton.tsxindex 20f34f9408c3..75da27f8078d 100644--- a/products/signals/frontend/inbox/components/detail/CreatePrButton.tsx+++ b/products/signals/frontend/inbox/components/detail/CreatePrButton.tsx@@ -35,14 +35,14 @@ const SLOT_CLAIM_DISABLED_REASON: Record<ImplementationSlotClaim, string> = {* reason.*/export function CreatePrButton({ report }: { report: SignalReport }): JSX.Element {- const { isCreatingPr, aiConsentDisabledReason } = useValues(inboxTaskKickoffLogic)+ const { isCreatingPr, createPrDisabledReason } = useValues(inboxTaskKickoffLogic)// Already mounted by `ReportDetail`, so this reads the loaded value rather than starting a fetch.const { implementationSlotClaim } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))const { createPrFromReport } = useActions(inboxTaskKickoffLogic)const [feedback, setFeedback] = useState('')const disabledReason =- aiConsentDisabledReason ??+ createPrDisabledReason ??(implementationSlotClaim ? SLOT_CLAIM_DISABLED_REASON[implementationSlotClaim] : undefined)const submit = (note: string): void => {@@ -51,8 +51,8 @@ export function CreatePrButton({ report }: { report: SignalReport }): JSX.Elemenif (isCreatingPr || implementationSlotClaim) {return}- if (aiConsentDisabledReason) {- lemonToast.error(aiConsentDisabledReason)+ if (createPrDisabledReason) {+ lemonToast.error(createPrDisabledReason)return}const trimmed = note.trim()diff --git a/products/signals/frontend/inbox/components/triage/InboxTriageView.tsx b/products/signals/frontend/inbox/components/triage/InboxTriageView.tsxindex 8226ee79dbb8..7d68de4353e4 100644--- a/products/signals/frontend/inbox/components/triage/InboxTriageView.tsx+++ b/products/signals/frontend/inbox/components/triage/InboxTriageView.tsx@@ -95,7 +95,7 @@ function HintBarItem({ shortcut, label }: { shortcut: JSX.Element; label: string}function TriageCard({ report, expanded }: { report: SignalReport; expanded: boolean }): JSX.Element {- const { canCreatePr, isCreatingPr, aiConsentDisabledReason, currentReportUrl } = useValues(inboxTriageLogic)+ const { canCreatePr, isCreatingPr, createPrDisabledReason, currentReportUrl } = useValues(inboxTriageLogic)const { dismissCurrent, resolveCurrent, createPrForCurrent, openCurrent, toggleExpanded } =useActions(inboxTriageLogic)@@ -216,7 +216,7 @@ function TriageCard({ report, expanded }: { report: SignalReport; expanded: boolicon={<IconPullRequest />}onClick={createPrForCurrent}loading={isCreatingPr}- disabledReason={aiConsentDisabledReason ?? undefined}+ disabledReason={createPrDisabledReason ?? undefined}sideIcon={<KeyboardShortcut c />}data-attr="inbox-triage-create-pr">diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.tsindex 6c825e689347..9e669b4390ac 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts@@ -1,8 +1,45 @@+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'+import { makeReport } from './__mocks__/inboxMocks'-import { buildCreatePrReportPrompt, buildDiscussReportPrompt } from './inboxTaskKickoffLogic'+import {+ FREE_TRIAL_PR_DISABLED_REASON,+ buildCreatePrReportPrompt,+ buildDiscussReportPrompt,+ inboxTaskKickoffLogic,+} from './inboxTaskKickoffLogic'import { SignalReportStatus } from './types'describe('inboxTaskKickoffLogic', () => {+ describe('freeTrialDisabledReason', () => {+ let logic: ReturnType<typeof inboxTaskKickoffLogic.build>++ beforeEach(() => {+ // featureFlagLogic persists to localStorage, which jsdom keeps across tests.+ localStorage.clear()+ initKeaTests()+ featureFlagLogic.mount()+ logic = inboxTaskKickoffLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it.each([+ [true, FREE_TRIAL_PR_DISABLED_REASON],+ [false, null],+ ])('with the free trial flag %s, Create PR carries %s', (enabled, expected) => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SELF_DRIVING_FREE_TRIAL], {+ [FEATURE_FLAGS.SELF_DRIVING_FREE_TRIAL]: enabled,+ })+ expect(logic.values.freeTrialDisabledReason).toBe(expected)+ })+ })+describe('buildDiscussReportPrompt', () => {const url = 'https://app.posthog.com/project/1/inbox/report-1'diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.tsindex eaefba7930d2..3eb13b7a25fb 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts@@ -4,6 +4,9 @@ import { router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { urls } from 'scenes/urls'@@ -31,6 +34,10 @@ import { aiConsentDisabledReason } from './utils/aiConsent'// NOT a live chat surface. The created task carries the SignalReport linkage so the// backend's agent pipeline can pick it up.+// Mirrors the server's `FREE_TRIAL_PR_MESSAGE`, so the disabled button and a refused call read the same.+export const FREE_TRIAL_PR_DISABLED_REASON =+ "During your free trial, Self-driving writes reports but doesn't open pull requests. Contact us to upgrade."+// The run endpoint rejects a model without its runtime adapter, so the two are always sent together.type ClaudeRuntimeSelection = Pick<ClaudeTaskRunCreateSchemaApi, 'runtime_adapter' | 'model' | 'reasoning_effort'>@@ -137,10 +144,15 @@ export function buildDiscussReportPrompt(report: SignalReport | null, reportUrl:// The per-report cap 429 carries code `signal_report_task_cap` with its message under `error`// (TaskRunErrorResponseSerializer); the per-user creation throttle is DRF's `throttled` 429 with-// `detail`. Both are user-facing copy the server owns. Matching on code, not status: other 429s-// (e.g. the compute-quota gate) are not task limits and belong on the generic failure path.+// `detail`; the free-trial refusal is a 402 with code `self_driving_free_trial` and `detail`. All+// are user-facing copy the server owns. Matching on code, not status: other 429s (e.g. the+// compute-quota gate) are not task limits and belong on the generic failure path.function taskLimitMessage(error: any): string | null {- if (error?.code === 'signal_report_task_cap' || error?.code === 'throttled') {+ if (+ error?.code === 'signal_report_task_cap' ||+ error?.code === 'throttled' ||+ error?.code === 'self_driving_free_trial'+ ) {return error?.data?.error || error?.detail || 'Task limit reached for this report. Try again later.'}return null@@ -213,7 +225,10 @@ async function createReportTask(export interface inboxTaskKickoffLogicValues {dataProcessingAccepted: boolean // aiConsentLogicdataProcessingApprovalDisabledReason: string | null // aiConsentLogic+ featureFlags: FeatureFlagsSet // featureFlagLogicaiConsentDisabledReason: string | null+ createPrDisabledReason: string | null+ freeTrialDisabledReason: string | nullisCreatingPr: booleanisDiscussing: boolean}@@ -257,6 +272,11 @@ export interface inboxTaskKickoffLogicMeta {dataProcessingAccepted: boolean,dataProcessingApprovalDisabledReason: string | null) => string | null+ freeTrialDisabledReason: (featureFlags: FeatureFlagsSet) => string | null+ createPrDisabledReason: (+ aiConsentDisabledReason: string | null,+ freeTrialDisabledReason: string | null+ ) => string | null}}@@ -271,7 +291,12 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([path(['scenes', 'inbox', 'inboxTaskKickoffLogic']),connect({- values: [aiConsentLogic, ['dataProcessingAccepted', 'dataProcessingApprovalDisabledReason']],+ values: [+ aiConsentLogic,+ ['dataProcessingAccepted', 'dataProcessingApprovalDisabledReason'],+ featureFlagLogic,+ ['featureFlags'],+ ],}),actions({@@ -308,6 +333,20 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([(dataProcessingAccepted: boolean, dataProcessingApprovalDisabledReason: string | null): string | null =>aiConsentDisabledReason(dataProcessingAccepted, dataProcessingApprovalDisabledReason),],+ // The flag is keyed on the organization group, so it resolves once the org group is+ // registered and flags are re-fetched. The server refuses the call regardless.+ freeTrialDisabledReason: [+ (s) => [s.featureFlags],+ (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): string | null =>+ featureFlags[FEATURE_FLAGS.SELF_DRIVING_FREE_TRIAL] ? FREE_TRIAL_PR_DISABLED_REASON : null,+ ],+ // Why Create PR is unavailable before any report is considered: consent first, then the+ // trial. Discuss keeps only the consent reason, because a trial org can still discuss.+ createPrDisabledReason: [+ (s) => [s.aiConsentDisabledReason, s.freeTrialDisabledReason],+ (aiConsentDisabledReason: string | null, freeTrialDisabledReason: string | null): string | null =>+ aiConsentDisabledReason ?? freeTrialDisabledReason,+ ],}),listeners(({ actions, values }) => ({@@ -359,13 +398,13 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([}},createPrFromReport: async ({ report, feedback }) => {- if (values.aiConsentDisabledReason) {- lemonToast.error(values.aiConsentDisabledReason)+ if (values.createPrDisabledReason) {+ lemonToast.error(values.createPrDisabledReason)captureInboxReportActionCompleted({report,actionType: 'create_pr',outcome: 'blocked',- blockedReason: values.aiConsentDisabledReason,+ blockedReason: values.createPrDisabledReason,})actions.createPrFailure()returndiff --git a/products/signals/frontend/inbox/logics/inboxTriageLogic.ts b/products/signals/frontend/inbox/logics/inboxTriageLogic.tsindex 77ed60f1cb9d..2c67428dcc2e 100644--- a/products/signals/frontend/inbox/logics/inboxTriageLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxTriageLogic.ts@@ -34,7 +34,7 @@ function clampIndex(index: number, length: number): number {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxTriageLogicValues {- aiConsentDisabledReason: string | null // inboxTaskKickoffLogic+ createPrDisabledReason: string | null // inboxTaskKickoffLogicisCreatingPr: boolean // inboxTaskKickoffLogichasMore: boolean // reportListLogicisLoaded: boolean // reportListLogic@@ -194,7 +194,7 @@ export const inboxTriageLogic = kea<inboxTriageLogicType>([reportListLogic(TRIAGE_LIST_PROPS),['reports', 'hasMore', 'isLoaded', 'reportsResponseLoading', 'reportsLoadFailed'],inboxTaskKickoffLogic,- ['isCreatingPr', 'aiConsentDisabledReason'],+ ['isCreatingPr', 'createPrDisabledReason'],],actions: [reportListLogic(TRIAGE_LIST_PROPS),@@ -405,7 +405,7 @@ export const inboxTriageLogic = kea<inboxTriageLogicType>([},createPrForCurrent: () => {const report = values.currentReport- if (!report || !values.canCreatePr || values.isCreatingPr || values.aiConsentDisabledReason) {+ if (!report || !values.canCreatePr || values.isCreatingPr || values.createPrDisabledReason) {return}// Triage is a fast keyboard flow with no note box, so it never steers the agent.diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex f2f395449d4b..75b0ffe2cd0e 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -1399,6 +1399,7 @@ def create_and_run_task(start_workflow: bool = True,branch: str | None = None,signal_report_id: str | None = None,+ free_trial_enabled: bool | None = None,internal: bool = False,sandbox_environment_id: str | None = None,channel_id: str | UUID | None = None,@@ -1413,6 +1414,10 @@ def create_and_run_task(``channel_id`` files the task into a channel's feed; left NULL for non-channel surfaces.An id the creator can't file into (see ``_visible_channel``) is ignored rather thanraising — feed placement must never break task creation.++ ``free_trial_enabled`` is a free-trial verdict the caller already resolved. Auto-start reads+ that flag before it takes the report row lock, so handing the result over keeps the flag+ request out of the lock. Left NULL, the gate reads the flag itself."""# create_pr=False sessions (research, repo selection, custom agents) can never open the# billable PR, so the quota gate must not block them.@@ -1421,6 +1426,9 @@ def create_and_run_task(# auto-start pipeline, whose over-quota hits must not pollute the manual-path# dark-launch bucket.enforce_self_driving_pr_quota(team, report_id=signal_report_id, stage="task_create")+ enforce_self_driving_free_trial(+ team, report_id=signal_report_id, stage="task_create", enabled=free_trial_enabled+ )channel = _visible_channel(channel_id, team.id, user_id) if channel_id is not None else Noneif channel is None and not internal and origin_product not in TEAM_READABLE_ORIGIN_PRODUCTS:channel = _ensure_personal_channel(team.id, user_id)[0]@@ -2645,6 +2653,32 @@ def _refresh_self_driving_quota_for_pr(run: TaskRun, old_pr_url: str | None) ->logger.warning("self_driving_quota_refresh_failed", extra={"run_id": str(run.id)}, exc_info=True)+def enforce_self_driving_free_trial(+ team: Team, *, report_id: str | None = None, stage: str = "manual_create", enabled: bool | None = None+) -> None:+ """Refuse to create or start a PR-opening self-driving task while the team's org is on a+ Self-driving free trial: a trial org gets reports, not pull requests, on any path (the+ auto-start gate in products/signals/backend/auto_start.py holds the pipeline back the same+ way). Emits `signal_report_free_trial_paused` at ``stage``. Raises+ ``FreeTrialPullRequestRefused`` (402, code ``self_driving_free_trial``) so clients can show+ the trial message.++ ``enabled`` takes a verdict the caller already resolved, and then the gate reads no flag of+ its own. A caller that holds a database lock resolves the flag before it takes the lock,+ because the read does network I/O.+ """+ from products.signals.backend.free_trial import ( # noqa: PLC0415 — cross-product read kept off the api import path+ FreeTrialPullRequestRefused,+ capture_signal_report_free_trial_paused,+ self_driving_free_trial_enabled,+ )++ if not (self_driving_free_trial_enabled(team) if enabled is None else enabled):+ return+ capture_signal_report_free_trial_paused(team, report_id=report_id, stage=stage)+ raise FreeTrialPullRequestRefused()++def enforce_self_driving_pr_quota(team: Team, *, report_id: str | None = None, stage: str = "manual_create") -> None:"""Refuse to create a PR-opening self-driving task while the team's org is over its self-drivingcredits quota with enforcement on. The implementation task is the step that leads to the@@ -6104,6 +6138,10 @@ def create_task()if signal_report_id:enforce_self_driving_pr_quota(team, report_id=signal_report_id)+ # Only Create PR is held back on a trial. Discuss keeps working, and a Discuss run can still+ # open a PR that billing never counts. That is an accepted risk of a sales trial.+ if signal_report_task_relationship in (None, "implementation"):+ enforce_self_driving_free_trial(team, report_id=signal_report_id)logger.info("Creating task with data: %s", validated_data)with transaction.atomic():@@ -7196,10 +7234,12 @@ def run_task(Returns ``None`` if the task isn't found/visible (the view raises 404). Otherwise a``TaskRunResult`` carrying the refreshed task detail DTO or a structured error. The usage- gate (429) is applied by the view before calling this.+ gate (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."""from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product read kept off the api import pathenforce_report_implementation_rerun_cap,+ is_report_implementation_task,)from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415get_task_run_artifacts_by_id,@@ -7223,6 +7263,17 @@ def run_task(else None)if 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)):+ enforce_self_driving_free_trial(+ Team.objects.select_related("organization").get(id=team_id),+ report_id=report_id_for_slot_check,+ stage="task_run",+ )# 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# avoids the sandbox and repository lookups a doomed run would otherwise do first. Thediff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 847f9595072f..0d3754ed1461 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -632,6 +632,14 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):],responses={201: TaskSerializer,+ 402: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description=(+ "The organization is on a Self-driving free trial, so a report implementation opens no "+ "pull request (code `self_driving_free_trial`), or the organization reached its "+ "self-driving pull request limit"+ ),+ ),403: OpenApiResponse(response=TaskRunErrorResponseSerializer,description="PostHog Desktop access is required for a create that can activate a warm sandbox",@@ -1152,6 +1160,13 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):responses={200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),+ 402: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description=(+ "The organization is on a Self-driving free trial, so a report implementation opens no "+ "pull request (code `self_driving_free_trial`)"+ ),+ ),403: OpenApiResponse(response=TaskRunErrorResponseSerializer,description="PostHog Desktop access is required, or Pi cloud runtime is disabled",diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex aa7e7f9fa443..2f8ea5892ef9 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -6,6 +6,7 @@ from uuid import UUID, uuid4from unittest.mock import MagicMock, patch+from django.apps import appsfrom django.db import close_old_connectionsfrom django.test import TestCase, TransactionTestCasefrom django.utils import timezone as django_timezone@@ -1954,3 +1955,138 @@ class TestOrganizationHasContext(TestCase):self.assertFalse(facade.organization_has_context(self.organization.id))self.assertTrue(facade.organization_has_context(other_org.id))+++class TestSelfDrivingFreeTrialFacadeGates(TestCase):+ organization: ClassVar[Organization]+ team: ClassVar[Team]+ user: ClassVar[User]++ @classmethod+ def setUpTestData(cls):+ cls.organization = Organization.objects.create(name="Trial Org")+ cls.team = Team.objects.create(organization=cls.organization, name="Trial Team")+ cls.user = User.objects.create(email="[email protected]", distinct_id="trial-facade-distinct")++ def _on_trial(self):+ return patch("products.signals.backend.free_trial.self_driving_free_trial_enabled", return_value=True)++ def _report(self):+ SignalReport = apps.get_model("signals", "SignalReport")+ return SignalReport.objects.create(team=self.team, status="ready", title="t", summary="s")++ @parameterized.expand([(None,), ("implementation",)])+ def test_create_task_refuses_create_pr_from_report_on_trial(self, relationship):+ # A trial org gets reports, not pull requests: the manual Create PR path is refused with+ # the trial code, so a client can show the trial message, and the held-back PR is counted.+ from products.signals.backend.free_trial import FreeTrialPullRequestRefused++ report = self._report()+ with (+ self._on_trial(),+ patch("products.signals.backend.free_trial.capture_signal_report_free_trial_paused") as capture_mock,+ self.assertRaises(FreeTrialPullRequestRefused) as raised,+ ):+ facade.create_task(+ self.team.id,+ self.user.id,+ validated_data={+ "title": "Implementation: t",+ "description": "d",+ "origin_product": Task.OriginProduct.SIGNAL_REPORT,+ "signal_report": report,+ "signal_report_task_relationship": relationship,+ },+ )+ self.assertEqual(raised.exception.get_codes(), "self_driving_free_trial")+ self.assertFalse(Task.objects.filter(team=self.team).exists())+ self.assertEqual(capture_mock.call_args.kwargs, {"report_id": str(report.id), "stage": "manual_create"})++ def test_create_task_allows_discussion_from_report_on_trial(self):+ # Discuss answers questions about a report and stays open on a trial; only Create PR is held back.+ report = self._report()+ with self._on_trial():+ dto = facade.create_task(+ self.team.id,+ self.user.id,+ validated_data={+ "title": "Discuss: t",+ "description": "d",+ "origin_product": Task.OriginProduct.SIGNAL_REPORT,+ "signal_report": report,+ "signal_report_task_relationship": "discussion",+ },+ )+ self.assertTrue(Task.objects.filter(id=dto.id).exists())++ @parameterized.expand([("implementation", True), ("discussion", False)])+ def test_run_task_refuses_an_existing_report_implementation_on_trial(self, relationship, expect_refusal):+ # The create-time gate cannot see a task that already existed when sales turned the flag+ # on. Starting or retrying that task opens the pull request the trial promises to withhold,+ # and bills the trial org for it. A discussion opens none, so it keeps running.+ from products.signals.backend.free_trial import FreeTrialPullRequestRefused+ 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=relationship+ )++ with (+ self._on_trial(),+ patch("products.signals.backend.free_trial.capture_signal_report_free_trial_paused") as capture_mock,+ patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"),+ ):+ if expect_refusal:+ with self.assertRaises(FreeTrialPullRequestRefused) as raised:+ facade.run_task(task.id, self.team.id, self.user.id, validated_data={"mode": "background"})+ self.assertEqual(raised.exception.get_codes(), "self_driving_free_trial")+ self.assertEqual(capture_mock.call_args.kwargs, {"report_id": str(report.id), "stage": "task_run"})+ else:+ result = facade.run_task(task.id, self.team.id, self.user.id, validated_data={"mode": "background"})+ assert result is not None and result.error is None+ self.assertEqual(task.runs.exists(), not expect_refusal)++ def test_create_and_run_task_refuses_pr_session_on_trial(self):+ # The facade backstop behind every PR-opening self-driving caller, with its own stage.+ from products.signals.backend.free_trial import FreeTrialPullRequestRefused++ with (+ self._on_trial(),+ patch("products.signals.backend.free_trial.capture_signal_report_free_trial_paused") as capture_mock,+ self.assertRaises(FreeTrialPullRequestRefused),+ ):+ facade.create_and_run_task(+ team=self.team,+ title="Implementation: t",+ description="d",+ origin_product=facade.TaskOriginProduct.SIGNAL_REPORT,+ user_id=self.user.id,+ repository="posthog/posthog",+ )+ self.assertFalse(Task.objects.filter(team=self.team).exists())+ self.assertEqual(capture_mock.call_args.kwargs["stage"], "task_create")++ def test_create_and_run_task_takes_a_pre_resolved_free_trial_verdict(self):+ # Auto-start resolves the flag before it takes the report row lock, so the create-time gate+ # must use the verdict it is given instead of making its own flag request under the lock.+ with self._on_trial() as flag_mock:+ dto = facade.create_and_run_task(+ team=self.team,+ title="Implementation: t",+ description="d",+ origin_product=facade.TaskOriginProduct.SIGNAL_REPORT,+ user_id=self.user.id,+ free_trial_enabled=False,+ start_workflow=False,+ )+ flag_mock.assert_not_called()+ self.assertTrue(Task.objects.filter(id=dto.task_id).exists())