: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 PR auto-refunds and system billing exemptions (#69066)
Alex Lebedev6e133cd2b97b
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 6d83dd9d73c0..979809573e73 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -236,6 +236,7 @@ rules:|SignalEmissionRecord|SignalReport|SignalReportArtefact+ |SignalReportRefund|SignalReportTask|SignalTeamConfig|SignalSourceConfig@@ -527,6 +528,7 @@ rules:|SignalEmissionRecord|SignalReport|SignalReportArtefact+ |SignalReportRefund|SignalReportTask|SignalTeamConfig|SignalSourceConfigdiff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.pyindex cdb8e46be9e9..435135a2c130 100644--- a/ee/billing/billing_manager.py+++ b/ee/billing/billing_manager.py@@ -74,6 +74,7 @@ def build_billing_token(user: Optional[User] = None,authorizer_actor: Optional[User] = None,billing_provider: BillingProvider | None = None,+ service_action: str | None = None,) -> str:"""Build the JWT token to authenticate with the Billing system.@@ -81,6 +82,10 @@ def build_billing_token(Allows doing privilege escalation with the `authorizer_actor` parameter, in that case the distinct_idwill be that of the user, but the role will be that of the authorizer_actor.+ `service_action` marks a token minted by a backend job for one specific service-to-service+ endpoint (e.g. "signals_pr_dispute"); billing rejects calls to such endpoints from tokens+ without the matching claim, so tokens minted for user-initiated calls can't reach them.+Raises NotAuthenticated if the authorizer_actor (or user in case there's no authorizer_actor) are notpart of the organization."""@@ -126,6 +131,9 @@ def build_billing_token(if billing_provider:payload["billing_provider"] = billing_provider.value+ if service_action:+ payload["service_action"] = service_action+encoded_jwt = jwt.encode(payload,license_secret,@@ -513,11 +521,17 @@ class BillingManager:organization: Organization,billing_provider: BillingProvider | None = None,authorizer_actor: User | None = None,+ service_action: str | None = None,):if not self.license: # mypyraise Exception("No license found")billing_service_token = build_billing_token(- self.license, organization, self.user, authorizer_actor=authorizer_actor, billing_provider=billing_provider+ self.license,+ organization,+ self.user,+ authorizer_actor=authorizer_actor,+ billing_provider=billing_provider,+ service_action=service_action,)return {"Authorization": f"Bearer {billing_service_token}"}@@ -556,6 +570,28 @@ class BillingManager:return res.json()+ def dispute_signals_pr(self, organization: Organization, data: dict[str, Any]) -> dict[str, Any]:+ """Ask billing to credit back a refunded Signals PR (idempotent on data['refund_id']).++ Billing returns 200 for every handled business outcome, including $0 credits; any other+ status means "not handled" and must raise so the caller retries. The default valid_codes+ would swallow 404 (endpoint not deployed) and 401 (auth failure) as success and record an+ error body as a synced credit, hence the explicit (200,).+ """+ res = requests.post(+ f"{BILLING_SERVICE_URL}/api/signals/dispute-pr",+ # The service_action claim is required by billing: it distinguishes this+ # backend-minted token from ones minted for user-initiated billing calls,+ # which cannot reach the dispute endpoint.+ headers=self.get_auth_headers(organization, service_action="signals_pr_dispute"),+ json=data,+ timeout=30,+ )++ handle_billing_service_error(res, valid_codes=(200,))++ return res.json()+def activate_trial(self, organization: Organization, data: dict[str, Any]):res = requests.post(f"{BILLING_SERVICE_URL}/api/trials/activate",diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.pyindex cd4dcced3d6c..34614f5e778e 100644--- a/ee/billing/quota_limiting.py+++ b/ee/billing/quota_limiting.py@@ -26,6 +26,7 @@ from posthog.models.team.team import Teamfrom posthog.redis import get_clientfrom posthog.tasks.usage_report import (convert_team_usage_rows_to_dict,+ get_signals_credited_refund_credits_for_org,get_teams_with_ai_credits_used_in_period,get_teams_with_ai_event_count_in_period,get_teams_with_api_queries_metrics,@@ -253,6 +254,30 @@ def is_team_over_ai_credit_budget(team_api_token: str) -> bool:# -------------------------------------------------------------------------------------------------+def _signals_credited_refund_offset(organization: Organization, resource: QuotaResource, over_limit: bool) -> int:+ """Quota offset for credited-path signals PR refunds, in signals credits.++ A credited refund fixes the money (a Stripe balance credit) but not the free-tier slot:+ billing's stored usage — what `usage_summary.signals_credits.usage` syncs from — still+ contains the refunded units, and signals has no grace period, so an over-limit org silently+ stops self-driving. This offset frees the slot posthog-side. Excluded-path refunds need+ nothing here: the same billing query drives `todays_usage`, so they drop out at the source.++ Only consulted when the org is at/over the limit before the offset, so the DB query fires for+ the handful of orgs that would otherwise be limited — not once per org in the all-orgs cron.+ The offset lives ONLY in the boolean limiting decision; the `todays_usage` written back into+ `organization.usage` stays truthful.+ """+ if resource != QuotaResource.SIGNALS_CREDITS or not over_limit:+ return 0+ period = (organization.usage or {}).get("period")+ if not period or len(period) < 2:+ return 0+ period_start = dateutil.parser.isoparse(period[0])+ period_end = dateutil.parser.isoparse(period[1])+ return get_signals_credited_refund_credits_for_org(organization.id, period_start, period_end)++def org_quota_limited_until(organization: Organization,resource: QuotaResource,@@ -271,6 +296,17 @@ def org_quota_limited_until(quota_limited_until = summary.get("quota_limited_until", None)quota_limiting_suspended_until = summary.get("quota_limiting_suspended_until", None)+ # Credited-path signals PR refunds free the org's quota slot posthog-side (billing's stored+ # usage still contains the refunded units). Consulted only when the raw comparison is already+ # at/over the limit, so the DB query fires for the handful of orgs that would otherwise be+ # limited. Surfaced on every quota event below for debuggability of refund-affected decisions.+ refund_offset = _signals_credited_refund_offset(+ organization,+ resource,+ limit is not None and usage + todays_usage >= limit + OVERAGE_BUFFER[resource],+ )+ refund_offset_properties = {"signals_refund_offset": refund_offset} if refund_offset else {}+if limit is None:if quota_limiting_suspended_until is not None or quota_limited_until is not None:report_organization_action(@@ -279,6 +315,7 @@ def org_quota_limited_until(properties={"event": "limit removed","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"quota_limited_until": quota_limited_until,"quota_limiting_suspended_until": quota_limiting_suspended_until,@@ -289,7 +326,7 @@ def org_quota_limited_until()return None- is_over_limit = usage + todays_usage >= limit + OVERAGE_BUFFER[resource]+ is_over_limit = usage + todays_usage - refund_offset >= limit + OVERAGE_BUFFER[resource]billing_period_start = round(dateutil.parser.isoparse(organization.usage["period"][0]).timestamp())billing_period_end = round(dateutil.parser.isoparse(organization.usage["period"][1]).timestamp())@@ -321,6 +358,7 @@ def org_quota_limited_until(properties={"event": "suspension removed","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"quota_limiting_suspended_until": quota_limiting_suspended_until,},@@ -338,6 +376,7 @@ def org_quota_limited_until(properties={"event": "ignored","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"never_drop_data": organization.never_drop_data,"trust_score": trust_score,@@ -361,6 +400,7 @@ def org_quota_limited_until(properties={"event": "already limited","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"quota_limited_until": billing_period_end,"quota_limiting_suspended_until": quota_limiting_suspended_until,@@ -389,6 +429,7 @@ def org_quota_limited_until(properties={"event": "ignored","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"feature_flag": QUOTA_LIMIT_DATA_RETENTION_FLAG,},@@ -422,6 +463,7 @@ def org_quota_limited_until(properties={"event": "suspended","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"trust_score": trust_score,},@@ -443,6 +485,7 @@ def org_quota_limited_until(properties={"event": "suspended","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"trust_score": trust_score,},@@ -471,6 +514,7 @@ def org_quota_limited_until(properties={"event": "suspended","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"grace_period_days": grace_period_days,"trust_score": trust_score,@@ -531,6 +575,7 @@ def org_quota_limited_until(properties={"event": "suspension not expired","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,"quota_limiting_suspended_until": quota_limiting_suspended_until,},@@ -552,6 +597,7 @@ def org_quota_limited_until(properties={"event": "suspended expired","current_usage": usage + todays_usage,+ **refund_offset_properties,"resource": resource.value,},)diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.pyindex f0c6b78e124a..b02dc3532de0 100644--- a/ee/billing/test/test_billing_manager.py+++ b/ee/billing/test/test_billing_manager.py@@ -646,6 +646,18 @@ class TestBuildBillingToken(BaseTest):assert "distinct_id" not in decodedassert "organization_role" not in decodedassert "original_role" not in decoded+ # Only service-to-service tokens carry service_action; billing uses its absence+ # to reject user-minted tokens on service-only endpoints.+ assert "service_action" not in decoded++ def test_build_billing_token_with_service_action(self):+ token = build_billing_token(self.license, self.organization, service_action="signals_pr_dispute")++ decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")++ assert decoded["service_action"] == "signals_pr_dispute"+ assert "distinct_id" not in decoded+ assert "organization_role" not in decodeddef test_build_billing_token_with_user_who_is_member(self):"""Token with user should include distinct_id and organization_role as level display string"""@@ -1365,3 +1377,50 @@ class TestRequestWithPostFallback(BaseTest):assert result == {"results": []}mock_get.assert_called_once()mock_post.assert_not_called()+++class TestDisputeSignalsPr(BaseTest):+ def _license(self) -> License:+ return super(LicenseManager, cast(LicenseManager, License.objects)).create(+ key="key123::key123",+ plan="enterprise",+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),+ )++ @patch(+ "ee.billing.billing_manager.requests.post",+ return_value=MagicMock(+ status_code=200,+ json=MagicMock(return_value={"credit_amount_usd": "15.00", "credit_id": "c1", "already_processed": False}),+ ),+ )+ def test_posts_to_dispute_endpoint_and_returns_body(self, billing_post_request_mock: MagicMock):+ payload = {"refund_id": "r1", "credits": 1500, "metadata": {}}++ result = BillingManager(self._license()).dispute_signals_pr(self.organization, payload)++ assert result == {"credit_amount_usd": "15.00", "credit_id": "c1", "already_processed": False}+ call_args = billing_post_request_mock.call_args+ assert call_args[0][0].endswith("/api/signals/dispute-pr")+ assert call_args[1]["json"] == payload+ assert "Authorization" in call_args[1]["headers"]+ # Billing only accepts dispute calls from tokens carrying the service_action+ # claim; without it the request is rejected as a user-initiated token.+ token = call_args[1]["headers"]["Authorization"].removeprefix("Bearer ")+ decoded = jwt.decode(token, options={"verify_signature": False})+ assert decoded["service_action"] == "signals_pr_dispute"+ assert "organization_role" not in decoded+ assert "distinct_id" not in decoded++ @parameterized.expand([("missing_deploy", 404), ("auth_failure", 401)])+ def test_raises_on_statuses_the_default_valid_codes_would_swallow(self, _name, status_code):+ # handle_billing_service_error's default valid_codes includes 404/401 — treating a missing+ # billing deploy or an auth failure as success would record an error body as a synced+ # credit. Any non-200 must raise so the Celery caller retries.+ response = MagicMock(status_code=status_code, json=MagicMock(return_value={"detail": "nope"}), ok=False)+ with patch("ee.billing.billing_manager.requests.post", return_value=response):+ with self.assertRaises(Exception) as context:+ BillingManager(self._license()).dispute_signals_pr(+ self.organization, {"refund_id": "r1", "credits": 1500, "metadata": {}}+ )+ assert str(status_code) in str(context.exception)diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.pyindex afd43f48a7f1..d1bcb7a97b06 100644--- a/ee/billing/test/test_quota_limiting.py+++ b/ee/billing/test/test_quota_limiting.py@@ -1,3 +1,4 @@+import datetimefrom typing import Any, castfrom uuid import uuid4@@ -5,6 +6,7 @@ from freezegun import freeze_timefrom posthog.test.base import BaseTest, FuzzyInt, _create_event, flush_persons_and_eventsfrom unittest.mock import patch+from django.apps import appsfrom django.test import override_settingsfrom django.utils import timezonefrom django.utils.timezone import now@@ -2756,3 +2758,89 @@ class TestUpdateOrganizationUsageFields(BaseTest):assert fresh.usage["events"]["usage"] == 0assert fresh.usage["events"]["limit"] == 10_000_000assert fresh.usage["period"] == ["2021-02-01T00:00:00Z", "2021-02-28T23:59:59Z"]+++class TestSignalsRefundQuotaOffset(BaseTest):+ # A free-plan signals org: limit == the 4500-credit free allocation (3 PRs).+ def _set_signals_usage(self, usage: int, *, todays_usage: int = 0) -> None:+ self.organization.usage = {+ "signals_credits": {"usage": usage, "todays_usage": todays_usage, "limit": 4500},+ "period": ["2026-06-01T00:00:00Z", "2026-07-01T00:00:00Z"],+ }+ self.organization.customer_trust_scores = {}+ self.organization.save()++ def _credited_refund(self, *, pr_run_created_at: datetime.datetime) -> None:+ # `ee` may not import `products.signals` (module boundaries), so reach its models via the+ # app registry at runtime — same pattern the signals tests use for the tasks product.+ SignalReport = apps.get_model("signals", "SignalReport")+ SignalReportRefund = apps.get_model("signals", "SignalReportRefund")+ report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.SUPPRESSED)+ SignalReportRefund.all_teams.create(+ team=self.team,+ report=report,+ reason=SignalReportRefund.Reason.PR_INCORRECT,+ billing_path=SignalReportRefund.BillingPath.CREDITED,+ credits=1500,+ pr_url="https://github.com/x/y/pull/1",+ pr_run_created_at=pr_run_created_at,+ )++ @parameterized.expand(+ [+ # At the free-tier limit (3 PRs billed), a credited refund of one PR frees the slot.+ ("in_period_refund_unlimits", datetime.datetime(2026, 6, 10, tzinfo=datetime.UTC), False),+ # A refund whose PR run predates the period must not grant this period a free slot.+ ("out_of_period_refund_keeps_limit", datetime.datetime(2026, 5, 10, tzinfo=datetime.UTC), True),+ ]+ )+ @patch("posthoganalytics.capture")+ @patch("posthoganalytics.feature_enabled", return_value=False)+ @freeze_time("2026-06-15T12:00:00Z")+ def test_credited_refund_offsets_quota_decision(+ self, _name, pr_run_created_at, expect_limited, _feature_enabled, _capture+ ) -> None:+ self._set_signals_usage(4500)+ self._credited_refund(pr_run_created_at=pr_run_created_at)++ result = org_quota_limited_until(self.organization, QuotaResource.SIGNALS_CREDITS, [], [])++ if expect_limited:+ assert result is not None+ assert result["quota_limited_until"] is not None+ else:+ assert result is None+ # The corruption regression: the offset lives only in the boolean decision — the stored+ # usage summary (what billing syncs and the UI reads) must stay untouched.+ self.organization.refresh_from_db()+ stored_usage = self.organization.usage+ assert stored_usage is not None+ assert stored_usage["signals_credits"]["usage"] == 4500+ assert stored_usage["signals_credits"]["todays_usage"] == 0++ @patch("posthoganalytics.capture")+ @patch("posthoganalytics.feature_enabled", return_value=False)+ @freeze_time("2026-06-15T12:00:00Z")+ def test_refund_lookup_skipped_when_under_limit(self, _feature_enabled, _capture) -> None:+ # The offset query must not run once per org in the all-orgs cron — only for orgs that+ # would otherwise be limited.+ self._set_signals_usage(1000)+ with patch("ee.billing.quota_limiting.get_signals_credited_refund_credits_for_org") as mock_offset:+ result = org_quota_limited_until(self.organization, QuotaResource.SIGNALS_CREDITS, [], [])+ assert result is None+ mock_offset.assert_not_called()++ @patch("posthoganalytics.capture")+ @patch("posthoganalytics.feature_enabled", return_value=False)+ @freeze_time("2026-06-15T12:00:00Z")+ def test_offset_ignores_other_resources(self, _feature_enabled, _capture) -> None:+ # An over-limit events org must never trigger the signals refund lookup.+ self.organization.usage = {+ "events": {"usage": 200, "todays_usage": 0, "limit": 100},+ "period": ["2026-06-01T00:00:00Z", "2026-07-01T00:00:00Z"],+ }+ self.organization.customer_trust_scores = {}+ self.organization.save()+ with patch("ee.billing.quota_limiting.get_signals_credited_refund_credits_for_org") as mock_offset:+ org_quota_limited_until(self.organization, QuotaResource.EVENTS, [], [])+ mock_offset.assert_not_called()diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 0d1e8918278a..35efd3c79315 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -224,6 +224,7 @@ export const FEATURE_FLAGS = {SETTINGS_SESSION_TABLE_VERSION: 'settings-session-table-version', // owner: #team-analytics-platformSETTINGS_SESSIONS_V2_JOIN: 'settings-sessions-v2-join', // owner: @robbie-c #team-web-analyticsSETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES: 'web-analytics-pre-aggregated-tables', // owner: @lricoy #team-web-analytics+ SIGNALS_PR_REFUNDS: 'signals-pr-refunds', // owner: #team-self-driving, gates the inbox PR refund flow (also checked server-side)SLACK_APP_OAUTH: 'slack-app-oauth', // owner: @VojtechBartos #team-platform-featuresSLOPE_GRAPH_INSIGHT: 'slope-graph-insight', // owner: @pauldambra #team-product-analyticsSTARTUP_PROGRAM_INTENT: 'startup-program-intent', // owner: @pawel-cebula #team-billingdiff --git a/frontend/src/scenes/inbox/components/badges/SignalReportBillingBadge.tsx b/frontend/src/scenes/inbox/components/badges/SignalReportBillingBadge.tsxnew file mode 100644index 000000000000..0ebd85db4310--- /dev/null+++ b/frontend/src/scenes/inbox/components/badges/SignalReportBillingBadge.tsx@@ -0,0 +1,48 @@+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import { SignalReport } from '../../types'++const EXEMPT_TOOLTIPS: Record<string, string> = {+ posthog_health_check:+ "This report was found by PostHog's automated health checks on its own systems, so its PR is free.",+ posthog_onboarding: 'This report was created during your onboarding setup run, so its PR is free.',+}++const EXEMPT_TOOLTIP_DEFAULT = "This report originates from PostHog's own systems, so its PR is free."++function refundTooltip(refund: NonNullable<SignalReport['refund']>): string {+ if (refund.billing_path === 'excluded') {+ return "This PR was refunded before it was ever billed – you won't pay for it and it doesn't count toward your included PRs."+ }+ if (refund.credit_amount_usd != null) {+ return `This PR was refunded – $${refund.credit_amount_usd} was credited toward your next invoice and it doesn't count toward your included PRs.`+ }+ return "This PR was refunded – the credit is being processed and it doesn't count toward your included PRs."+}++/**+ * Permanent billing marker for a report: "Refunded" once its PR has been refunded, or "Free" when+ * the report is system-marked never-billable (PostHog-system origin, e.g. a health-check scout+ * finding). Null for ordinary billable reports.+ */+export function SignalReportBillingBadge({ report }: { report: SignalReport }): JSX.Element | null {+ if (report.refund) {+ return (+ <Tooltip title={refundTooltip(report.refund)}>+ <LemonTag size="small" type="completion">+ Refunded+ </LemonTag>+ </Tooltip>+ )+ }+ if (report.billing_exempt_reason) {+ return (+ <Tooltip title={EXEMPT_TOOLTIPS[report.billing_exempt_reason] ?? EXEMPT_TOOLTIP_DEFAULT}>+ <LemonTag size="small" type="success">+ Free+ </LemonTag>+ </Tooltip>+ )+ }+ return null+}diff --git a/frontend/src/scenes/inbox/components/cards/ReportCard.tsx b/frontend/src/scenes/inbox/components/cards/ReportCard.tsxindex ae6d6a1e4cea..acaf6f143288 100644--- a/frontend/src/scenes/inbox/components/cards/ReportCard.tsx+++ b/frontend/src/scenes/inbox/components/cards/ReportCard.tsx@@ -18,6 +18,7 @@ import {safeHttpUrl,} from '../../utils/reportPresentation'import { SignalReportActionabilityBadge } from '../badges/SignalReportActionabilityBadge'+import { SignalReportBillingBadge } from '../badges/SignalReportBillingBadge'import { SignalReportPriorityBadge } from '../badges/SignalReportPriorityBadge'import { SignalReportStatusBadge } from '../badges/SignalReportStatusBadge'import {@@ -162,7 +163,7 @@ export function ReportCard({}): JSX.Element {const isArchived = tabKey === 'archived'// Resolved reports are terminal (their implementation PR merged) – shown for reference in the- // Archive tab but with no row action: they can't be restored or re-archived.+ // Archive tab. They can't be restored or re-archived; refunding their PR lives in the detail pane.const isResolved = report.status === SignalReportStatus.RESOLVEDconst prUrl = safeHttpUrl(report.implementation_pr_url)const prUrlParts = prUrl ? parsePrUrlParts(prUrl) : null@@ -185,22 +186,29 @@ export function ReportCard({onArchive,})+ const isRefunded = !!report.refund+// On the Archive tab, surface why it was dismissed (reason tag + note tooltip) when we have it.// Key off the report still being suppressed, not the tab: a report that was dismissed, restored,// then resolved keeps its old dismissal artefact, and showing that tag would mislabel finished work.+ // The dedicated billing badge already marks refunded reports, so skip the duplicate chip there.const dismissalLabel =- isArchived && report.status === SignalReportStatus.SUPPRESSED+ isArchived && report.status === SignalReportStatus.SUPPRESSED && !isRefunded? dismissalReasonLabel(report.dismissal_reason): null+ // Permanent billing marker (Refunded / Free) — shown on both PR cards and plain reports.+ const showBillingBadge = isRefunded || !!report.billing_exempt_reason+// PR cards show repo · source; reports show source · status · actionability.const showMeta = hasPr- ? repoSlug != null || hasSource+ ? repoSlug != null || hasSource || showBillingBadge: hasSource ||!isReady ||report.actionability != null ||report.is_suggested_reviewer === true ||- !!dismissalLabel+ !!dismissalLabel ||+ showBillingBadgereturn (<div className={clsx('relative', inboxCardRowClassName(attached, { dashed: !hasPr }))}>@@ -273,6 +281,7 @@ export function ReportCard({</LemonTag></Tooltip>)}+ <SignalReportBillingBadge report={report} /></div>) : null}@@ -287,24 +296,30 @@ export function ReportCard({</div></Link>- {/* Terminal resolved reports carry no row action – skip the action column (and its divider). */}- {!isResolved && (+ {/* Refund deliberately isn't offered at the card level – it lives in the report detail+ pane, where the consequences are in view. Resolved reports are terminal and a refunded+ archived report can't be restored, so neither carries actions – skip the column (and+ divider) for both. */}+ {!isResolved && !(isArchived && isRefunded) && (<div className="flex items-center justify-end gap-2.5 shrink-0 @lg:self-stretch @lg:border-l @lg:border-primary @lg:pl-3">{isArchived ? (- <LemonButton- type="secondary"- size="small"- icon={<IconUndo />}- tooltip="Restore this report to the inbox"- aria-label="Restore this report to the inbox"- onClick={(event) => {- event.preventDefault()- event.stopPropagation()- onRestore?.()- }}- >- Restore- </LemonButton>+ // A refunded report can't be restored (its PR can never be billed again).+ !isRefunded && (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconUndo />}+ tooltip="Restore this report to the inbox"+ aria-label="Restore this report to the inbox"+ onClick={(event) => {+ event.preventDefault()+ event.stopPropagation()+ onRestore?.()+ }}+ >+ Restore+ </LemonButton>+ )) : (<><LemonButtondiff --git a/frontend/src/scenes/inbox/components/cards/useReportRefund.ts b/frontend/src/scenes/inbox/components/cards/useReportRefund.tsnew file mode 100644index 000000000000..ddb55ea75066--- /dev/null+++ b/frontend/src/scenes/inbox/components/cards/useReportRefund.ts@@ -0,0 +1,99 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { lemonToast } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { teamLogic } from 'scenes/teamLogic'++import { signalsReportsRefundCreate } from 'products/signals/frontend/generated/api'++import { captureInboxReportAction, InboxReportActionSurface } from '../../inboxAnalytics'+import { SignalReport } from '../../types'+import { openRefundReportDialog } from '../shell/RefundReportDialog'++// Copy per backend `refund_ineligibility_reason`. `already_refunded` / `billing_exempt` never+// reach the button (it's hidden for those), so only the two visible-but-ineligible reasons map.+const REFUND_DISABLED_REASONS: Record<string, string> = {+ out_of_period: 'This PR was billed in a previous billing period and can no longer be refunded',+ no_billable_pr: "This PR isn't billable, so there's nothing to refund",+}++/**+ * Shared refund handler for the inbox cards and the detail pane, mirroring `useReportArchive`.+ * Opens the refund dialog and posts to the refund endpoint; the backend freezes the billing path,+ * archives the report, and (when needed) kicks off the billing credit. Offered only when the flag+ * is on and the report has a billable PR that hasn't been refunded — the server enforces the same+ * rules, so `canRefund` is purely a display gate.+ */+export function useReportRefund({+ report,+ surface,+ onRefunded,+}: {+ report: SignalReport+ /** Which surface the refund was triggered from, for the `refund` analytics. */+ surface?: InboxReportActionSurface+ /** Fired once the refund API call succeeds (the report is archived server-side by then). */+ onRefunded?: () => void+}): {+ canRefund: boolean+ refundDisabledReason: string | null+ isRefunding: boolean+ onRefundClick: (event: React.MouseEvent) => void+} {+ const { featureFlags } = useValues(featureFlagLogic)+ const { currentTeamId } = useValues(teamLogic)+ const [isRefunding, setIsRefunding] = useState(false)++ // Exempt reports ("Free" tag) were never charged, so there is nothing to refund; a report+ // without a PR was never billed either. One refund per report, ever.+ const canRefund =+ !!featureFlags[FEATURE_FLAGS.SIGNALS_PR_REFUNDS] &&+ !!report.implementation_pr_url &&+ !report.refund &&+ !report.billing_exempt_reason++ // Backend-owned eligibility: when the visible button would only ever 400 (e.g. the PR was+ // billed in a previous period), disable it with the reason instead of hiding it.+ const refundDisabledReason =+ canRefund && report.refund_ineligibility_reason+ ? (REFUND_DISABLED_REASONS[report.refund_ineligibility_reason] ?? "This PR can't be refunded right now")+ : null++ const onRefundClick = (event: React.MouseEvent): void => {+ event.preventDefault()+ event.stopPropagation()+ openRefundReportDialog({+ reportTitle: report.title,+ onConfirm: async ({ reason, note }) => {+ if (isRefunding || currentTeamId == null) {+ return+ }+ setIsRefunding(true)+ try {+ await signalsReportsRefundCreate(String(currentTeamId), report.id, {+ reason,+ ...(note ? { note } : {}),+ })+ captureInboxReportAction({+ report,+ actionType: 'refund',+ surface: surface ?? 'list_row',+ extra: { refund_reason: reason, ...(note ? { refund_note: note } : {}) },+ })+ lemonToast.success("PR refunded – you won't be charged for it")+ onRefunded?.()+ } catch (error: any) {+ lemonToast.error(error?.detail || error?.error || error?.message || 'Failed to refund this PR')+ throw error // keep the dialog open so the user can retry+ } finally {+ setIsRefunding(false)+ }+ },+ })+ }++ return { canRefund, refundDisabledReason, isRefunding, onRefundClick }+}diff --git a/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx b/frontend/src/scenes/inbox/components/detail/ReportDetail.tsxindex 21d371527f63..c2bb32c7a357 100644--- a/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx+++ b/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx@@ -24,6 +24,7 @@ import {safeHttpUrl,} from '../../utils/reportPresentation'import { SignalReportActionabilityBadge } from '../badges/SignalReportActionabilityBadge'+import { SignalReportBillingBadge } from '../badges/SignalReportBillingBadge'import { SignalReportPriorityBadge } from '../badges/SignalReportPriorityBadge'import { SignalReportStatusBadge } from '../badges/SignalReportStatusBadge'import {@@ -64,6 +65,7 @@ export function ReportDetailBadges({actionability={report.actionability}explanation={actionabilityExplanation}/>+ <SignalReportBillingBadge report={report} /></>)}@@ -127,6 +129,7 @@ function ReportDetailMeta({actionability={report.actionability}explanation={actionabilityExplanation}/>+ <SignalReportBillingBadge report={report} /><span className="flex items-center gap-2 flex-wrap min-w-0">{stats.map((node, i) => (<span key={i} className="flex items-center gap-2 min-w-0">@@ -302,7 +305,7 @@ export function InboxDetailFrame({const overflowMenuItems: LemonMenuItem[] = reportActions.map((action) => ({label: action.label,icon: action.icon,- disabledReason: action.loading ? 'Working…' : undefined,+ disabledReason: action.loading ? 'Working…' : action.disabledReason,onClick: action.onClick,}))@@ -411,7 +414,9 @@ export function InboxDetailFrame({size="small"icon={action.icon}loading={action.loading}- tooltip={action.tooltip}+ // A disabled action explains only why it's unavailable — not what it would do.+ tooltip={action.disabledReason ? undefined : action.tooltip}+ disabledReason={action.disabledReason}onClick={action.onClick}>{action.label}diff --git a/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx b/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsxindex adc9e505cd0d..d64f604f8114 100644--- a/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx+++ b/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { type MouseEvent, useState } from 'react'-import { IconArchive, IconMessage, IconPullRequest, IconUndo } from '@posthog/icons'+import { IconArchive, IconMessage, IconPullRequest, IconReceipt, IconUndo } from '@posthog/icons'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'@@ -15,6 +15,7 @@ import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'import { INBOX_FLAT_TAB_LIST_PARAMS, reportListLogic } from '../../logics/reportListLogic'import { ACTIONABLE_ACTIONABILITY_VALUES, SignalReport, SignalReportStatus } from '../../types'import { useReportArchive } from '../cards/useReportArchive'+import { useReportRefund } from '../cards/useReportRefund'import { openFeedbackReportDialog } from '../shell/FeedbackReportDialog'/**@@ -29,6 +30,8 @@ export interface ReportDetailAction {onClick: (event: MouseEvent) => voidloading?: booleantooltip?: string+ /** Renders the action disabled with this explanation (e.g. a PR past its refund window). */+ disabledReason?: string}/**@@ -61,6 +64,7 @@ export function useReportDetailActions(report: SignalReport): ReportDetailActionconst { createPrFromReport } = useActions(inboxTaskKickoffLogic)const { reportArchived } = useActions(inboxBulkActionsLogic)const { activeTab } = useValues(inboxSceneLogic)+ const { loadSelectedReport } = useActions(inboxSceneLogic)const [isRestoring, setIsRestoring] = useState(false)const showCreatePr = canCreateImplementationPr(report)@@ -81,6 +85,33 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction},})+ const { canRefund, refundDisabledReason, isRefunding, onRefundClick } = useReportRefund({+ report,+ surface: 'detail_pane',+ // Refunding archives the report server-side, so reconcile the lists the same way and+ // return to the list — except for resolved reports, which stay where they are.+ onRefunded: () => {+ reportArchived()+ if (report.status !== SignalReportStatus.RESOLVED) {+ router.actions.push(urls.inbox(activeTab))+ } else {+ // Resolved reports stay on this page, so refetch: the fresh copy carries `refund`,+ // which surfaces the Refunded badge and drops Refund from the actions.+ loadSelectedReport({ id: report.id })+ }+ },+ })++ const refund: ReportDetailAction = {+ key: 'refund',+ label: 'Refund',+ icon: <IconReceipt />,+ loading: isRefunding,+ tooltip: "Refund this PR – you won't pay for it and it won't count toward your included PRs",+ disabledReason: refundDisabledReason ?? undefined,+ onClick: onRefundClick,+ }+const onRestoreClick = async (): Promise<void> => {// Prefer the mounted Archived list logic so it optimistically drops the row and fixes its// count + tab badge synchronously (it also fires the API call + toast). Navigate straight back.@@ -125,23 +156,31 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction}),}- // A resolved report is terminal – its PR already merged, so only feedback applies.+ // A resolved report is terminal – its PR already merged, so only feedback applies. The PR can+ // still be refunded (auto-approved by design; the weekly review watches refunded-then-merged).if (isResolved) {- return [feedback]+ return [feedback, ...(canRefund ? [refund] : [])]}- // An already-archived report offers Restore instead of Archive (and no Create PR).+ // An already-archived report offers Restore instead of Archive (and no Create PR). A refunded+ // report can't be restored (its PR can never be billed again), so Restore is hidden for it; an+ // archived-but-still-charged report can still be refunded.if (isArchived) {return [feedback,- {- key: 'restore',- label: 'Restore',- icon: <IconUndo />,- loading: isRestoring,- tooltip: 'Restore this report to your inbox',- onClick: () => void onRestoreClick(),- },+ ...(canRefund ? [refund] : []),+ ...(report.refund+ ? []+ : [+ {+ key: 'restore',+ label: 'Restore',+ icon: <IconUndo />,+ loading: isRestoring,+ tooltip: 'Restore this report to your inbox',+ onClick: () => void onRestoreClick(),+ },+ ]),]}@@ -155,6 +194,7 @@ export function useReportDetailActions(report: SignalReport): ReportDetailActiontooltip: 'Archive this report out of your inbox',onClick: onArchiveClick,},+ ...(canRefund ? [refund] : []),]if (showCreatePr) {diff --git a/frontend/src/scenes/inbox/components/shell/RefundReportDialog.tsx b/frontend/src/scenes/inbox/components/shell/RefundReportDialog.tsxnew file mode 100644index 000000000000..bb4be1c1449b--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/RefundReportDialog.tsx@@ -0,0 +1,66 @@+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonRadio, LemonRadioOption } from 'lib/lemon-ui/LemonRadio'+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'++import { SignalReportRefundReasonEnumApi } from 'products/signals/frontend/generated/api.schemas'++export interface RefundReportDialogResult {+ reason: SignalReportRefundReasonEnumApi+ note: string+}++interface OpenRefundReportDialogParams {+ /** Report title for the dialog copy. */+ reportTitle?: string | null+ /** Called with the chosen reason + note once the user confirms. */+ onConfirm: (result: RefundReportDialogResult) => void | Promise<void>+}++// Values are the backend `SignalReportRefund.Reason` choices (via the generated enum); the future+// refund judge consumes them, so the labels spell out what each code means.+const REFUND_REASON_OPTIONS: LemonRadioOption<SignalReportRefundReasonEnumApi>[] = [+ { value: SignalReportRefundReasonEnumApi.PrIncorrect, label: "The PR doesn't fix what the report describes" },+ { value: SignalReportRefundReasonEnumApi.PrNotUseful, label: 'The PR works but is not useful to me' },+ { value: SignalReportRefundReasonEnumApi.Duplicate, label: 'Duplicate of work already covered' },+ { value: SignalReportRefundReasonEnumApi.Other, label: 'Something else…' },+]++/**+ * Opens the refund dialog (mirrors {@link openDismissReportDialog}): pick a required reason plus an+ * optional note, then refund. The caller wires `onConfirm` to the refund API call; refunding also+ * archives the report, so the copy says both. `shouldAwaitSubmit` keeps the primary button in a+ * loading state while the request is in flight, so it can't be double-submitted.+ */+export function openRefundReportDialog({ reportTitle, onConfirm }: OpenRefundReportDialogParams): void {+ LemonDialog.openForm({+ title: `Refund the PR for "${reportTitle?.trim() ? reportTitle : 'Untitled report'}"?`,+ description:+ "You won't pay for this PR and it won't count toward your included PRs. The report is archived as part of the refund and can't be restored.",+ maxWidth: '30rem',+ initialValues: { reason: null as SignalReportRefundReasonEnumApi | null, note: '' },+ content: (+ <div className="flex flex-col gap-3">+ <LemonField name="reason" label="Reason">+ {({ value, onChange }) => (+ <LemonRadio value={value} onChange={onChange} options={REFUND_REASON_OPTIONS} />+ )}+ </LemonField>+ <LemonField name="note" label="Note" info="Optional – helps us review refunds">+ <LemonTextArea placeholder="Optional: add detail" maxLength={4000} rows={3} />+ </LemonField>+ </div>+ ),+ errors: {+ reason: (reason) => (!reason ? "You haven't picked a reason" : undefined),+ },+ primaryButtonProps: { children: 'Refund' },+ shouldAwaitSubmit: true,+ onSubmit: async ({ reason, note }) => {+ if (!reason) {+ return+ }+ await onConfirm({ reason, note: (note ?? '').trim() })+ },+ })+}diff --git a/frontend/src/scenes/inbox/inboxAnalytics.ts b/frontend/src/scenes/inbox/inboxAnalytics.tsindex d6d1d28d3361..17ce27f560b1 100644--- a/frontend/src/scenes/inbox/inboxAnalytics.ts+++ b/frontend/src/scenes/inbox/inboxAnalytics.ts@@ -45,6 +45,7 @@ export type InboxReportActionType =| 'dismiss'| 'restore'| 'create_pr'+ | 'refund'| 'add_suggested_reviewer'| 'remove_suggested_reviewer'diff --git a/frontend/src/scenes/inbox/logics/inboxUsageLogic.test.ts b/frontend/src/scenes/inbox/logics/inboxUsageLogic.test.tsnew file mode 100644index 000000000000..69d9ce44b8a5--- /dev/null+++ b/frontend/src/scenes/inbox/logics/inboxUsageLogic.test.ts@@ -0,0 +1,71 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { SignalReportRefundSummaryResponseApi } from 'products/signals/frontend/generated/api.schemas'++import { inboxUsageLogic } from './inboxUsageLogic'++const CREDITS_PER_PR = 1500++const mountWithUsage = async (+ currentUsage: number,+ summary: Omit<SignalReportRefundSummaryResponseApi, 'credited_refund_count'>+): Promise<ReturnType<typeof inboxUsageLogic.build>> => {+ useMocks({+ get: {+ '/api/billing': () => [+ 200,+ { products: [{ type: 'inbox', display_divisor: CREDITS_PER_PR, current_usage: currentUsage }] },+ ],+ '/api/projects/:team_id/signals/reports/refund-summary/': () => [+ 200,+ { credited_refund_count: summary.credited_credits / CREDITS_PER_PR, ...summary },+ ],+ },+ })+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SIGNALS_PR_REFUNDS], {+ [FEATURE_FLAGS.SIGNALS_PR_REFUNDS]: true,+ })+ const logic = inboxUsageLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ return logic+}++describe('inboxUsageLogic', () => {+ let logic: ReturnType<typeof inboxUsageLogic.build> | undefined++ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ })++ // usedPrs must read `max(billing's recorded usage, live billable credits) − credited refunds`:+ // recorded usage lags up to a day, so a just-created PR (and its same-day excluded-path refund)+ // is only visible through the live count, while credited-path refunds stay in recorded usage+ // and must be netted out. Each row pins one side of that contract.+ it.each([+ // [case, billing current_usage, live period credits, credited credits, expected PRs]+ ['counts a just-created PR that billing has not recorded yet', 1500, 3000, 0, 2],+ ['drops when a same-day refund removes the PR from live usage', 1500, 1500, 0, 1],+ ['nets credited-path refunds out of recorded usage', 9000, 9000, 1500, 5],+ ['clamps at zero when credited refunds exceed billed usage', 0, 1500, 3000, 0],+ ])('%s', async (_case, currentUsage, periodBillableCredits, creditedCredits, expectedPrs) => {+ logic = await mountWithUsage(currentUsage, {+ period_billable_credits: periodBillableCredits,+ credited_credits: creditedCredits,+ })++ expect(logic.values.usedPrs).toBe(expectedPrs)+ })+})diff --git a/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts b/frontend/src/scenes/inbox/logics/inboxUsageLogic.tsindex 0331494384bc..fb5f10e37ce7 100644--- a/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts+++ b/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts@@ -1,12 +1,20 @@import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { forms } from 'kea-forms'+import { loaders } from 'kea-loaders'+import { FEATURE_FLAGS } from 'lib/constants'import { Dayjs } from 'lib/dayjs'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { calculateFreeTier } from 'scenes/billing/billing-utils'import { billingLogic } from 'scenes/billing/billingLogic'+import { teamLogic } from 'scenes/teamLogic'import { BillingProductV2Type } from '~/types'+import { signalsReportsRefundSummaryRetrieve } from 'products/signals/frontend/generated/api'+import type { SignalReportRefundSummaryResponseApi } from 'products/signals/frontend/generated/api.schemas'++import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'import type { inboxUsageLogicType } from './inboxUsageLogicType'// The inbox/signals billing product type (a flat per-PR credit charge). This is the identifier@@ -38,13 +46,40 @@ function perCreditUsd(product: BillingProductV2Type): number | null {export const inboxUsageLogic = kea<inboxUsageLogicType>([path(['scenes', 'inbox', 'logics', 'inboxUsageLogic']),connect(() => ({- values: [billingLogic, ['billing', 'billingLoading', 'canAccessBilling']],+ values: [+ billingLogic,+ ['billing', 'billingLoading', 'canAccessBilling'],+ featureFlagLogic,+ ['featureFlags'],+ teamLogic,+ ['currentTeamId'],+ ],actions: [billingLogic, ['loadBilling', 'updateBillingLimits']],})),actions({openModal: true,closeModal: true,}),+ loaders(({ values }) => ({+ // Credited-path refund totals for the org's current billing period. Billing usage still+ // contains credited-refunded PRs (the money comes back as an invoice credit, not lower+ // usage), so the widget subtracts these to show the net PR count. Excluded-path refunds+ // never reach billing usage and need no adjustment.+ // TODO(signals): usage + refund summary are org-wide (billing allocates the free PR tier+ // per org), but this widget renders on a project-routed page where the number can read as+ // project usage — label it org-wide, or revisit if billing ever splits usage per project.+ refundSummary: [+ null as SignalReportRefundSummaryResponseApi | null,+ {+ loadRefundSummary: async (): Promise<SignalReportRefundSummaryResponseApi | null> => {+ if (!values.featureFlags[FEATURE_FLAGS.SIGNALS_PR_REFUNDS] || values.currentTeamId == null) {+ return null+ }+ return await signalsReportsRefundSummaryRetrieve(String(values.currentTeamId))+ },+ },+ ],+ })),reducers({isModalOpen: [false,@@ -89,8 +124,17 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([billing?.products?.find((p) => p.type === INBOX_PRODUCT_TYPE) ?? null,],isLoading: [- (s) => [s.billing, s.billingLoading],- (billing, billingLoading): boolean => billing === null && billingLoading,+ (s) => [s.billing, s.billingLoading, s.refundSummary, s.refundSummaryLoading, s.featureFlags],+ (billing, billingLoading, refundSummary, refundSummaryLoading, featureFlags): boolean => {+ if (billing === null && billingLoading) {+ return true+ }+ // With refunds on, the PR count needs the refund summary too (live top-up ++ // credited netting) — rendering on billing alone briefly shows the gross number.+ return (+ !!featureFlags[FEATURE_FLAGS.SIGNALS_PR_REFUNDS] && refundSummary === null && refundSummaryLoading+ )+ },],// Free plan can't raise the limit past the free allocation — the widget points to// billing to upgrade instead of editing a limit.@@ -117,9 +161,21 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([product && creditsPerPr ? Math.round(calculateFreeTier(product) / creditsPerPr) : 0,],usedPrs: [- (s) => [s.product, s.creditsPerPr],- (product, creditsPerPr): number =>- product && creditsPerPr ? Math.round((product.current_usage ?? 0) / creditsPerPr) : 0,+ (s) => [s.product, s.creditsPerPr, s.refundSummary],+ (product, creditsPerPr, refundSummary): number => {+ if (!product || !creditsPerPr) {+ return 0+ }+ // Billing's recorded usage lags by up to a day; the refund summary carries the org's+ // live billable credits, so take the max — a just-created PR counts immediately and a+ // same-day (excluded-path) refund visibly un-counts it.+ const billedCredits = Math.max(product.current_usage ?? 0, refundSummary?.period_billable_credits ?? 0)+ const billedPrs = Math.round(billedCredits / creditsPerPr)+ // Credited-path refunds stay in billing usage; net them out so the widget counts+ // only PRs the user is actually paying (or using free allowance) for.+ const refundedPrs = refundSummary ? Math.floor(refundSummary.credited_credits / creditsPerPr) : 0+ return Math.max(0, billedPrs - refundedPrs)+ },],customLimitUsd: [(s) => [s.billing, s.product],@@ -204,10 +260,15 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([// Seed the field with the current limit (or the free allowance when uncapped).actions.setLimitFormValue('prs', values.limitPrs ?? values.freePrs)},+ // Refunds broadcast `reportArchived` after archiving server-side; reload the summary so+ // the widget's netted PR count updates in-session (mirrors the reportListLogic reconcile+ // listener — a plain archive just makes this a cheap no-op reload).+ [inboxBulkActionsLogic.actionTypes.reportArchived]: () => actions.loadRefundSummary(),})),afterMount(({ actions, values }) => {if (!values.billing) {actions.loadBilling()}+ actions.loadRefundSummary()}),])diff --git a/frontend/src/scenes/inbox/types.ts b/frontend/src/scenes/inbox/types.tsindex 2bc150deb19e..617127e8a332 100644--- a/frontend/src/scenes/inbox/types.ts+++ b/frontend/src/scenes/inbox/types.ts@@ -1,6 +1,7 @@import type { UserBasicType } from '~/types'import {+ type SignalReportRefundApi,SignalSourceProductApi as SignalSourceProduct,SignalSourceTypeApi as SignalSourceType,} from 'products/signals/frontend/generated/api.schemas'@@ -75,6 +76,12 @@ export interface SignalReport {dismissal_reason?: string | null/** Free-form note from the latest dismissal artefact (when archived). */dismissal_note?: string | null+ /** The report's PR refund, when one exists (one refund per report, ever). */+ refund?: SignalReportRefundApi | null+ /** Non-null when the report is system-marked never-billable (PostHog-system origin) — its PR is free. */+ billing_exempt_reason?: string | null+ /** Backend-owned refund eligibility: why a refund would be rejected right now, null when it would be accepted. */+ refund_ineligibility_reason?: string | null}export enum SignalReportStatus {diff --git a/frontend/src/scenes/inbox/utils/dismissalReasons.ts b/frontend/src/scenes/inbox/utils/dismissalReasons.tsindex 74f20118f6e6..1f3422e9464b 100644--- a/frontend/src/scenes/inbox/utils/dismissalReasons.ts+++ b/frontend/src/scenes/inbox/utils/dismissalReasons.ts@@ -31,6 +31,13 @@ export const DISMISSAL_REASON_OPTIONS = [/** Persisted dismissal / suppress reason (values match {@link DISMISSAL_REASON_OPTIONS}). */export type DismissalReasonValue = (typeof DISMISSAL_REASON_OPTIONS)[number]['value']+// Reason codes persisted by flows outside the dismiss dialog (never user-selectable there), so the+// dismissal chip still renders a label instead of the raw code. `refunded` is written by the PR+// refund action, which archives the report as part of the refund.+const EXTRA_DISMISSAL_REASON_LABELS: Record<string, string> = {+ refunded: 'Refunded',+}+/** Whether the given reason snoozes the report (temporarily) instead of permanently dismissing it. */export function isDismissalReasonSnooze(value: DismissalReasonValue): boolean {const option = DISMISSAL_REASON_OPTIONS.find((o) => o.value === value)@@ -42,5 +49,7 @@ export function dismissalReasonLabel(value: string | null | undefined): string |if (!value) {return null}- return DISMISSAL_REASON_OPTIONS.find((o) => o.value === value)?.label ?? value+ return (+ DISMISSAL_REASON_OPTIONS.find((o) => o.value === value)?.label ?? EXTRA_DISMISSAL_REASON_LABELS[value] ?? value+ )}diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 28c7714f698a..3dae32bb17b6 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -535,6 +535,7 @@ SPECTACULAR_SETTINGS = {# both the no-x-spec-enum-id type-hint path and the inline-choices ChoiceField# path (drf-spectacular generates the x-spec-enum-id from the same tuples).# --- Model class paths (ChoiceField x-spec-enum-id hashes) ---+ "SignalReportRefundReasonEnum": "products.signals.backend.models.SignalReportRefund.Reason","EngineeringAnalyticsPRStateEnum": "products.engineering_analytics.backend.facade.contracts.PRState","QuarantineModeEnum": "products.engineering_analytics.backend.facade.contracts.QuarantineMode","RestrictionLevelEnum": "products.dashboards.backend.models.dashboard.Dashboard.RestrictionLevel",diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex c5df63cca64d..cb9e6c571cd5 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -92,6 +92,7 @@ from products.feature_flags.backend.tasks import ()from products.logs.backend.facade.tasks import logs_alert_events_cleanup_taskfrom products.reminders.backend.tasks import process_due_reminders+from products.signals.backend.tasks import sync_pending_signals_refund_creditsfrom products.streamlit_apps.backend.facade.api import (auto_restart_crashed_streamlit_sandboxes,cleanup_deleted_streamlit_app_zips,@@ -258,6 +259,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="redispatch orphaned queued task runs",)+ # Re-enqueue signals PR refunds whose billing credit sync hasn't landed - hourly at minute 25+ sender.add_periodic_task(+ crontab(hour="*", minute="25"),+ sync_pending_signals_refund_credits.s(),+ name="sync pending signals refund credits",+ )+# Flags cache sync - hourlysender.add_periodic_task(crontab(hour="*", minute="15"),diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex 6e36664da793..94524d8a3362 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -1,6 +1,7 @@import osimport gzipimport json+import uuidimport base64import loggingimport dataclasses@@ -52,7 +53,7 @@ from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.error_tracking.backend.facade import api as error_tracking_apifrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.replay_vision.backend.billing import get_replay_vision_credits_by_team-from products.signals.backend.billing import get_signals_billing_credits_by_team+from products.signals.backend.billing import credited_refund_credits_for_org, get_signals_billing_credits_by_teamfrom products.surveys.backend.models import Surveyfrom products.surveys.backend.util import (SurveyEventProperties,@@ -1568,6 +1569,18 @@ def get_teams_with_signals_credits_used_in_period(return get_signals_billing_credits_by_team(begin, end)+def get_signals_credited_refund_credits_for_org(+ organization_id: str | uuid.UUID, begin: datetime, end: datetime+) -> int:+ """Credits returned via credited-path signals PR refunds in `[begin, end)` for one org.++ Input to the quota-limiting offset — see `products/signals/backend/billing.py`. Re-exported+ from this posthog-layer module (like the usage query above) because the module boundaries+ allow posthog → products.signals but not ee → products.signals.+ """+ return credited_refund_credits_for_org(organization_id, begin, end)++@timed_log()@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)def get_teams_with_posthog_code_credits_used_in_period(diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex e30c9561446e..41d525a2606e 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1107,6 +1107,25 @@ Signal {index}:---+## Testing refunds locally++How to exercise the PR refund flow (`backend/billing.py`, the `refund` action, the credited-path billing sync) against a fully local two-service setup:++1. **Billing service**: follow "Developing locally" in the billing repo's README (boots on `http://localhost:8100`).+ The dispute endpoint (`POST /api/signals/dispute-pr`) must exist on the billing checkout.+ Dev mode auto-creates the `License` and `Customer` rows on first authenticated call — nothing to seed there.+2. **Posthog**: start the stack with `BILLING_SERVICE_URL=http://localhost:8100` visible to **both** the web backend and the celery worker (put it in `.env.local`, which wins over `.env.development`).+ The dev license auto-creates as `…::license-so-secret`, matching billing's default `LICENSE_SECRET_KEY`; a stale `ee_license` row with a different secret is the classic JWT-auth failure — check `SELECT key FROM ee_license;`.+3. **Feature flag**: `signals-pr-refunds` must exist, active at 100%, in the local self-capture project (create via UI or shell; `sync_feature_flags` also works but flips every flag).+ Without it the refund endpoints return **404**. Backend picks it up within the ~90s SDK poll (or restart); the frontend needs a page reload.+4. **Data**: `python manage.py seed_refund_test_data --team-id 1` seeds the full matrix — excluded-path (PR today), credited-path (PR yesterday), billing-exempt, and a no-PR exemption-command target.+5. **Expectations**: with an unseeded billing side the credited path legitimately returns `credit_amount_usd = "0.00"` — that IS the success path (free plan → nothing to credit). Non-$0 outcomes (`"15.00"` with paid-tier usage) require seeding a paid inbox state on the billing side; the recipe, a posthog-free curl smoke test, and how to verify the Stripe balance transaction live in the billing repo (internal): `notes/testing-signals-disputes-locally.md`.+ Inspecting the paid state via the posthog billing page (`/organization/billing`) additionally requires **organization owner** — local dev users are typically only `administrator`, so bump `OrganizationMembership.level` to `OWNER` (15) first.+ Verify `billing_synced_at`/`credit_amount_usd` on `signals_signalreportrefund` (posthog) and, for non-$0 outcomes, the `Credit` row keyed `signals_pr_dispute:{billing_customer_id}:{refund_id}` (billing). $0 outcomes persist nothing billing-side (`credit_id: null` in the response) — the refund row is the whole record.+ Celery-side analytics events (`signals_pr_refund_credit_issued`/`_failed`) are dropped locally (`ph_scoped_capture` is cloud-gated); the sync itself is unaffected.++---+## File Map```textdiff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex 06200ca2117e..8d8f03c7ddc7 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -6,13 +6,20 @@ from typing import TypedDict, TypeVarfrom django.db import transactionimport structlog+import posthoganalyticsfrom pydantic import BaseModel, ValidationError+from posthog.event_usage import groupsfrom posthog.models import Team, Userfrom posthog.models.organization import OrganizationMembershipfrom posthog.sync import database_sync_to_asyncfrom products.signals.backend.agent_runtime import STEP_IMPLEMENTATION, resolve_agent_runtime+from products.signals.backend.billing import (+ BillingExemptionError,+ mark_report_billing_exempt,+ system_billing_exempt_reason,+)from products.signals.backend.models import (SignalReport,SignalReportArtefact,@@ -28,6 +35,7 @@ from products.signals.backend.report_generation.research import ()from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_usersfrom products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.signal_metadata import fetch_source_products_for_reportsfrom products.signals.backend.slack_inbox_notifications import POSTHOG_CODE_INBOX_DEEP_LINK_SCHEMEfrom products.signals.backend.task_run_artefacts import (SIGNALS_PRODUCT,@@ -111,6 +119,51 @@ def _build_autostart_task_description()+def _stamp_billing_exemption(report: SignalReport, declared_reason: str | None) -> str | None:+ """Freeze the report's billing exemption (caller-declared origin first, then system policy)+ under the auto-start row lock, before the implementation task — and therefore any billable PR+ run — can exist. Prospective-only by construction; returns the reason when the report ends up+ exempt, None when it stays billable."""+ reason = declared_reason or system_billing_exempt_reason(report.team_id, str(report.id))+ if reason:+ try:+ mark_report_billing_exempt(report, reason)+ except BillingExemptionError:+ # A billable PR run already exists; a late "should have been free" is a refund, never+ # a flag flip (it would break usage-report determinism). Stay billable.+ logger.warning(+ "signals billing exemption skipped: billable PR run already exists",+ report_id=str(report.id),+ team_id=report.team_id,+ )+ return report.billing_exempt_reason+++def _capture_billing_exempted(*, team: Team, report_id: str, reason: str, task_id: str) -> None:+ """`signals_pr_billing_exempted` — exempt volume is a cost signal for the weekly refund review."""+ try:+ source_products: list[str] = []+ meta = fetch_source_products_for_reports(team, [report_id]).get(report_id)+ if meta is not None:+ source_products = meta.source_products+ posthoganalytics.capture(+ event="signals_pr_billing_exempted",+ distinct_id=str(team.organization.id),+ properties={+ "team_id": team.id,+ "organization_id": str(team.organization.id),+ "report_id": report_id,+ "task_id": task_id,+ "reason": reason,+ "source_products": source_products,+ },+ groups=groups(team.organization, team),+ )+ except Exception:+ # Analytics must never break auto-start.+ logger.exception("Failed to capture signals_pr_billing_exempted", report_id=report_id)++def _create_implementation_task_if_absent(*,team_id: int,@@ -120,6 +173,7 @@ def _create_implementation_task_if_absent(user_id: int,repository: str,base_branch: str | None,+ billing_exempt_reason: str | None = None,) -> bool:"""Create the implementation task and record it (gate row + work-log artefact), serialized per report.@@ -130,10 +184,15 @@ def _create_implementation_task_if_absent(inside the lock makes the decision atomic: the second evaluation blocks, then sees the gate andreturns ``False``. Returns ``True`` if it created the task, ``False`` if one already exists / thereport is gone.++ The same lock is where billing exemptions freeze (`_stamp_billing_exemption`): the reason is+ decided and written before the task exists, so it can never race a billable PR run."""# Resolved outside the transaction: the flag read does network I/O and must not hold the row lock.agent_runtime = resolve_agent_runtime(team_id, STEP_IMPLEMENTATION)+ exempt_reason: str | None = None+ task_id: str | None = Nonewith transaction.atomic():report = SignalReport.objects.select_for_update().filter(id=report_id, team_id=team_id).first()if report is None:@@ -148,6 +207,7 @@ def _create_implementation_task_if_absent(report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION):return False+ exempt_reason = _stamp_billing_exemption(report, billing_exempt_reason)team = Team.objects.select_related("organization").get(id=team_id)created = tasks_facade.create_and_run_task(team=team,@@ -173,15 +233,20 @@ def _create_implementation_task_if_absent()if created.latest_run is None:raise RuntimeError(f"Task {created.task_id} auto-started without producing a TaskRun")+ task_id = str(created.task_id)# Written inside the lock so the gate check above and this write are serialized — the# `SignalReportTask` gate row must be visible before the lock releases.record_implementation_task(team_id=team_id,report_id=report_id,- task_id=str(created.task_id),+ task_id=task_id,run_id=str(created.latest_run.id),)- return True+ if exempt_reason and task_id:+ # After commit: the exempt report's implementation task exists — count it (includes a+ # best-effort ClickHouse lookup, so it must not run under the lock).+ _capture_billing_exempted(team=team, report_id=report_id, reason=exempt_reason, task_id=task_id)+ return Truedef _resolve_autostart_assignee(@@ -323,6 +388,7 @@ async def maybe_autostart_implementation_task(reviewers_content: list[ReviewerContent],priority: PriorityAssessment | None,triggering_user_id: int | None = None,+ billing_exempt_reason: str | None = None,) -> None:"""Start an implementation Task for a SignalReport if autonomy + priority allow it.@@ -333,6 +399,11 @@ async def maybe_autostart_implementation_task(agent / scout, whose reviewers come from commit authorship), the assignee is resolved from*reviewers_content*.+ ``billing_exempt_reason`` lets a caller that knows its origin is PostHog-system (e.g. a future+ report-linked onboarding run) declare the report never-billable up front. Independently of it,+ system policy (`billing.system_billing_exempt_reason`) marks exempt-origin reports — either+ way the reason freezes under the row lock before the task (and any billable PR run) exists.+Idempotent: skipped if an implementation task already started for the report(a `SignalReportTask` implementation gate row), if the report is not immediatelyactionable, if it's already addressed, or if priority is missing. The "already@@ -417,6 +488,7 @@ async def maybe_autostart_implementation_task(user_id=task_user.id,repository=repository,base_branch=base_branch,+ billing_exempt_reason=billing_exempt_reason,)if not created:# Another evaluation won the race and already created the implementation task.diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.pyindex b79bba15e189..fefc8c2f5d0a 100644--- a/products/signals/backend/billing.py+++ b/products/signals/backend/billing.py@@ -16,16 +16,44 @@ produce a charge.Credits use the same unit as ai_credits: 1 credit = $0.01, so the flat $15 charge is 1500credits.++Two mechanisms remove a report from billing:++- **Refunds** (retrospective, `SignalReportRefund`): an `excluded`-path refund makes the usage+ query skip the report entirely — committed strictly on the same UTC day as the first billable+ PR run, so no usage send (all of which happen ≥3h45m into the next UTC day) can ever observe+ the exclusion flipping. A `credited`-path refund is deliberately NOT consulted here: usage+ stays truthful and the money comes back as a billing-service credit.+- **Exemptions** (prospective, `SignalReport.billing_exempt_reason`): PostHog-system-origin+ reports are marked never-billable before their billable moment exists, so they never enter+ usage (nor, via the same query driving quota `todays_usage`, consume a free-tier slot).++Emergent semantic to be aware of: because of the `billed_earlier` idempotency check below, a+report whose first billable PR run has been refunded can NEVER be billed again — a later, second+PR run on the same report finds the first run before the period and is skipped, and the first+run itself is refund-excluded (excluded path) or already handled by a credit (credited path).+This is why restoring a refunded report is blocked at the API layer: refund → restore → new PR+would otherwise be repeatable free work."""import uuidfrom collections import defaultdictfrom datetime import datetime+from typing import TYPE_CHECKING, NamedTuple++from django.db.models import F, OuterRef, QuerySet, Subquery, Sum+from django.utils import timezone-from django.db.models import F, QuerySet+from dateutil.relativedelta import relativedeltafrom products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION-from products.signals.backend.models import SignalReportTask+from products.signals.backend.enums import SignalSourceProduct+from products.signals.backend.models import SignalReport, SignalReportRefund, SignalReportTask, SignalScoutRun+from products.signals.backend.scout_harness.lazy_seed import scout_skill_row_origin+from products.skills.backend.models.skills import LLMSkill++if TYPE_CHECKING:+ from posthog.models.organization import Organization_IMPLEMENTATION = TASK_RUN_TYPE_IMPLEMENTATION@@ -68,14 +96,211 @@ def _bridges_with_pr_run(**run_created_at: datetime) -> QuerySet[SignalReportTas)-def get_signals_billing_credits_by_team(begin: datetime, end: datetime) -> list[tuple[int, int]]:+class BillingExemptionError(Exception):+ """A report can no longer be exempted — a billable PR run already exists (use a refund)."""+++# PostHog-system scout skills whose reports must never bill — users must not pay for PRs that fix+# problems in PostHog's own systems. v1 policy is this code constant; the report→scout link is the+# runs' `emitted_report_ids` tally (report-channel scouts author their reports directly).+BILLING_EXEMPT_SCOUT_SKILLS: dict[str, str] = {+ "signals-scout-health-checks": SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK,+}++# Same policy for the signal channel: sources owned by PostHog systems (e.g. the temporal+# health-checks pipeline, `posthog/temporal/health_checks/signal_emitter.py`). Per-signal+# source_product never reaches Postgres, so this map is enforced where the report row is+# formed — the grouping activity stamps `billing_exempt_reason` at creation. Formation-time+# only: an exempt-origin signal joining an existing report never flips it (and vice versa),+# mirroring `mark_report_billing_exempt`'s first-reason-wins freeze.+BILLING_EXEMPT_SOURCE_PRODUCTS: dict[str, str] = {+ SignalSourceProduct.HEALTH_CHECKS: SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK,+}+++def _scout_skill_is_canonical(team_id: int, skill_name: str) -> bool:+ """Whether the team's row for `skill_name` is still the PostHog-shipped scout, byte for byte.++ `skill_name` alone doesn't attest PostHog-system origin: a team can edit a seeded scout in+ place and the diverged row keeps its canonical name, which would let a repurposed fork mint+ permanent exemptions. `scout_skill_row_origin` settles it by content hash against the+ fingerprint stamped at seed time. Fails closed — no row, no proof → billable.+ """+ skill = LLMSkill.objects.filter(team_id=team_id, name=skill_name, deleted=False, is_latest=True).first()+ return skill is not None and scout_skill_row_origin(skill) == "canonical"+++def system_billing_exempt_reason(team_id: int, report_id: str | uuid.UUID) -> str | None:+ """The exemption reason system policy assigns to a report, or None for normal reports.++ Pure Postgres (no ClickHouse), so it is usable under the auto-start row lock: a report is+ exempt-origin when an exempt scout skill's run authored it via `emit_report` — and the+ team's row for that skill is still the canonical PostHog-shipped content (a team-edited+ fork keeps the name but is no longer PostHog's system, so its reports stay billable).+ """+ for skill_name, reason in BILLING_EXEMPT_SCOUT_SKILLS.items():+ if (+ SignalScoutRun.objects.for_team(team_id)+ .filter(skill_name=skill_name, emitted_report_ids__contains=[str(report_id)])+ .exists()+ ) and _scout_skill_is_canonical(team_id, skill_name):+ return reason+ return None+++def mark_report_billing_exempt(report: SignalReport, reason: str) -> bool:+ """Mark `report` never-billable, enforcing the prospective-only freeze rule (hard).++ Returns False (no-op) when the report already carries an exemption — the first reason wins,+ exemptions are never rewritten. Raises `BillingExemptionError` when the report already has a+ billable PR run: anything already billable is a refund, never a late exemption, so no usage+ report can ever observe this field flipping.++ Persists only the exemption column (deliberately not bumping `updated_at` — a billing-internal+ stamp must not resurface the report in recency-ordered lists). Callers needing atomicity with+ other writes should hold the report row lock; the auto-start hook does.+ """+ if reason not in SignalReport.BillingExemptReason.values:+ raise ValueError(f"Unknown billing exemption reason: {reason!r}")+ if report.billing_exempt_reason:+ return False+ if first_billable_pr_run_at(report.id) is not None:+ raise BillingExemptionError(+ f"Report {report.id} already has a billable PR run; use a refund instead of a billing exemption."+ )+ report.billing_exempt_reason = reason+ report.save(update_fields=["billing_exempt_reason"])+ return True+++class FirstBillablePrRun(NamedTuple):+ created_at: datetime+ pr_url: str+++def first_billable_pr_run(report_id: str | uuid.UUID) -> FirstBillablePrRun | None:+ """The report's billable moment: its first implementation run with a GitHub PR URL (with that+ run's `created_at` and `pr_url`), or None if it has never shipped one.++ Single source of truth for "when did this report become chargeable" — the refund action uses+ it for eligibility, snapshots, and the UTC-day path decision, and the exemption freeze rule+ uses it to refuse late exemptions. It applies the exact same fail-closed filters as the usage+ query, so the two can never disagree about whether a billable run exists.+ """+ row = (+ _bridges_with_pr_run()+ .filter(report_id=report_id)+ # Both columns resolve against the TaskRun join the filter established, so the earliest+ # billable run's timestamp and URL come from the same row.+ .order_by("task__runs__created_at")+ .values_list("task__runs__created_at", "task__runs__output__pr_url")+ .first()+ )+ if row is None:+ return None+ return FirstBillablePrRun(created_at=row[0], pr_url=row[1])+++def first_billable_pr_run_at(report_id: str | uuid.UUID) -> datetime | None:+ """`first_billable_pr_run`, timestamp only."""+ run = first_billable_pr_run(report_id)+ return run.created_at if run else None+++def annotate_first_billable_pr_run_at(queryset: QuerySet[SignalReport]) -> QuerySet[SignalReport]:+ """Annotate each report with `first_billable_pr_run_at` (its billable moment, batched form of+ `first_billable_pr_run`), NULL when it never shipped a billable PR run. Applies the same+ fail-closed filters as the usage query, so list-rendered refund eligibility can never+ disagree with what the refund action would accept."""+ earliest = (+ _bridges_with_pr_run()+ .filter(report_id=OuterRef("id"))+ .order_by("task__runs__created_at")+ .values("task__runs__created_at")[:1]+ )+ return queryset.annotate(first_billable_pr_run_at=Subquery(earliest))+++# Why a report can't be refunded right now (`refund_ineligibility_reason`); None = refundable.+REFUND_INELIGIBLE_ALREADY_REFUNDED = "already_refunded"+REFUND_INELIGIBLE_BILLING_EXEMPT = "billing_exempt"+REFUND_INELIGIBLE_NO_BILLABLE_PR = "no_billable_pr"+REFUND_INELIGIBLE_OUT_OF_PERIOD = "out_of_period"++REFUND_INELIGIBILITY_REASONS = (+ REFUND_INELIGIBLE_ALREADY_REFUNDED,+ REFUND_INELIGIBLE_BILLING_EXEMPT,+ REFUND_INELIGIBLE_NO_BILLABLE_PR,+ REFUND_INELIGIBLE_OUT_OF_PERIOD,+)+++def refund_ineligibility_reason(+ *,+ has_refund: bool,+ billing_exempt: bool,+ billable_run_at: datetime | None,+ period: tuple[datetime, datetime],+) -> str | None:+ """Why a report can't be refunded right now, or None when a refund would be accepted.++ The single eligibility decision, shared by the refund action (which maps each reason to its+ 400/idempotent response) and the report serializer (which exposes the reason so the UI can+ disable the Refund button) — the button state can never drift from what the POST enforces.+ """+ if has_refund:+ return REFUND_INELIGIBLE_ALREADY_REFUNDED+ if billing_exempt:+ return REFUND_INELIGIBLE_BILLING_EXEMPT+ if billable_run_at is None:+ return REFUND_INELIGIBLE_NO_BILLABLE_PR+ period_start, period_end = period+ if not (period_start <= billable_run_at < period_end):+ return REFUND_INELIGIBLE_OUT_OF_PERIOD+ return None+++def credited_refund_credits_for_org(organization_id: str | uuid.UUID, begin: datetime, end: datetime) -> int:+ """Sum of `credits` over the org's credited-path refunds whose refunded PR run falls in+ `[begin, end)` — the amount the quota check offsets so a credited refund frees the free-tier+ slot, not just the money. Keyed on `pr_run_created_at` (not refund creation) so the offset+ lines up with the period the usage was billed in. Unscoped: deliberately org-wide."""+ return (+ SignalReportRefund.objects.unscoped()+ .filter(+ team__organization_id=organization_id,+ billing_path=SignalReportRefund.BillingPath.CREDITED,+ pr_run_created_at__gte=begin,+ pr_run_created_at__lt=end,+ )+ .aggregate(total=Sum("credits"))["total"]+ or 0+ )+++def current_billing_period_bounds(organization: "Organization") -> tuple[datetime, datetime]:+ """The org's current billing period `[start, end)`, falling back to the current UTC calendar+ month when billing hasn't populated `organization.usage["period"]` (e.g. self-hosted or a+ just-created org). Refund eligibility and the org-wide refund summary both key off this."""+ period = organization.current_billing_period+ if period is not None:+ return period+ now = timezone.now()+ start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)+ return (start, start + relativedelta(months=1))+++def get_signals_billing_credits_by_team(+ begin: datetime, end: datetime, organization_id: str | uuid.UUID | None = None+) -> list[tuple[int, int]]:"""Signals credits used per team in `[begin, end)`.A report is billable in this period when the first implementation PR for it appeared in thewindow — an implementation `TaskRun` with a `pr_url` was created in `[begin, end)` and nosuch run exists before `begin`. Each billable report is charged a flat`SIGNALS_CREDITS_PER_REPORT_WITH_PR`. Returns `[(team_id, credits), ...]` for teams with- non-zero usage only.+ non-zero usage only. `organization_id` narrows the scan to one org (the widget's live-count+ path); usage reporting passes nothing and stays fleet-wide.The entry scan is bounded by PRs shipped in the period (via the `created_at` +`output__pr_url` indexes), not by the total number of reports, task runs, or teams.@@ -83,11 +308,14 @@ def get_signals_billing_credits_by_team(begin: datetime, end: datetime) -> list[# Reports whose implementation produced a billable PR within this period, mapped to the team# that owns the report. The teams are guaranteed equal by `_bridges_with_pr_run()`, so the# bridge's team_id is the report's team.- report_team: dict[uuid.UUID, int] = {}- for report_id, team_id in _bridges_with_pr_run(+ bridges = _bridges_with_pr_run(task__runs__created_at__gte=begin,task__runs__created_at__lt=end,- ).values_list("report_id", "team_id"):+ )+ if organization_id is not None:+ bridges = bridges.filter(team__organization_id=organization_id)+ report_team: dict[uuid.UUID, int] = {}+ for report_id, team_id in bridges.values_list("report_id", "team_id"):report_team.setdefault(report_id, team_id)if not report_team:@@ -104,10 +332,43 @@ def get_signals_billing_credits_by_team(begin: datetime, end: datetime) -> list[.values_list("report_id", flat=True))+ # Excluded-path refunds: billing must never learn these reports existed. Deterministic across+ # re-sends by the UTC-day path rule (see module docstring). Credited-path refunds are+ # deliberately absent — their usage stays truthful. Unscoped: this aggregates across all teams+ # outside any request context.+ refund_excluded = set(+ SignalReportRefund.objects.unscoped()+ .filter(report_id__in=report_ids, billing_path=SignalReportRefund.BillingPath.EXCLUDED)+ .values_list("report_id", flat=True)+ )++ # Billing-exempt reports (PostHog-system origins) never bill; the reason is frozen before the+ # billable moment exists, so this is deterministic across re-sends too.+ billing_exempt = set(+ # nosemgrep: idor-lookup-without-team (ids come from the team-grouped billing bridge query above; usage aggregation is deliberately cross-team)+ SignalReport.objects.filter(id__in=report_ids, billing_exempt_reason__isnull=False).values_list("id", flat=True)+ )++ skipped = billed_earlier | refund_excluded | billing_exempt+totals: dict[int, int] = defaultdict(int)for report_id, team_id in report_team.items():- if report_id in billed_earlier:+ if report_id in skipped:continuetotals[team_id] += SIGNALS_CREDITS_PER_REPORT_WITH_PRreturn list(totals.items())+++def period_billable_credits_for_org(organization_id: str | uuid.UUID, begin: datetime, end: datetime) -> int:+ """The org's billable signals credits for `[begin, end)` per the exact usage-report rules —+ including PRs created today that haven't been reported to billing yet.++ Powers the inbox usage widget's live PR count: the frontend takes the max of this and+ billing's recorded usage, so a fresh PR counts immediately and a same-UTC-day (excluded-path)+ refund visibly un-counts it. Display-only — usage reports never read this; credited-path+ refunds stay included here (usage is truthful) and are netted separately by the widget.+ """+ return sum(+ credits for _, credits in get_signals_billing_credits_by_team(begin, end, organization_id=organization_id)+ )diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.mdindex 40a8f5aa3987..18ff9c8e7270 100644--- a/products/signals/backend/management/AGENTS.md+++ b/products/signals/backend/management/AGENTS.md@@ -74,6 +74,24 @@ in `relevant_commit_hashes` to map to a user with a `SignalUserAutonomyConfig` wpriority threshold (personal or team default) covers the report's priority — otherwise thereport will be saved but no `Task` will be created.+## Seeding billable reports (refund testing)++`seed_refund_test_data` drops five minimal reports covering the refund/exemption matrix:+PR-run-today (refund takes the `excluded` path), PR-run-4-days-ago (`credited` path — calls the+billing dispute endpoint), PR-run-last-month (out of the billing period — the Refund button+renders disabled with the reason), billing-exempt with a PR ("Free" badge with health-check+tooltip; refund hidden), and no-PR (target for `exempt_signal_report_billing`). Re-run freely —+a report can only be refunded once.++```bash+python manage.py seed_refund_test_data --team-id 1+```++`seed_inbox_data` reports are billable too (runs are recorded via the production dual-write),+but their runs are created "now", so refunds on them always take the excluded path.+Environment prerequisites (feature flag, local billing service): "Testing refunds locally"+in `../../ARCHITECTURE.md`.+## Re-ingesting reports`reingest_signal_report` deletes specific reports and re-emits their signals through the activediff --git a/products/signals/backend/management/commands/cleanup_signals.py b/products/signals/backend/management/commands/cleanup_signals.pyindex 5322e8f766ec..5fc5e476d414 100644--- a/products/signals/backend/management/commands/cleanup_signals.py+++ b/products/signals/backend/management/commands/cleanup_signals.py@@ -8,7 +8,7 @@ from posthog.models import Teamfrom products.error_tracking.backend.embedding import PARTITIONED_SHARDED_DOCUMENT_EMBEDDINGSfrom products.error_tracking.backend.indexed_embedding import EMBEDDING_TABLES-from products.signals.backend.models import SignalReport, SignalReportArtefact+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportRefundfrom products.signals.backend.temporal.buffer import BufferSignalsWorkflowfrom products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflowfrom products.signals.backend.temporal.summary import SignalReportSummaryWorkflow@@ -80,6 +80,8 @@ class Command(BaseCommand):SignalReportArtefact.objects.filter(team=team).delete()self.stdout.write(f"Deleting {report_count} SignalReports...")+ # Refunds RESTRICT report deletion; a dev wipe means everything goes.+ SignalReportRefund.objects.for_team(team.id).delete()SignalReport.objects.filter(team=team).delete()# 3. Terminate Temporal workflowsdiff --git a/products/signals/backend/management/commands/exempt_signal_report_billing.py b/products/signals/backend/management/commands/exempt_signal_report_billing.pynew file mode 100644index 000000000000..409e39a1cb30--- /dev/null+++ b/products/signals/backend/management/commands/exempt_signal_report_billing.py@@ -0,0 +1,49 @@+"""Ops escape hatch: mark a signal report never-billable (system billing exemption).++For ad-hoc cases the auto-start policy doesn't cover. Prospective-only, like every exemption+setter: refuses once the report has a billable PR run — anything already billable is handled as a+refund, never a late exemption (flipping the flag after billing may have observed the run would+break usage-report determinism).+"""++from typing import Any++from django.core.management.base import BaseCommand, CommandError++from products.signals.backend.billing import BillingExemptionError, mark_report_billing_exempt+from products.signals.backend.models import SignalReport+++class Command(BaseCommand):+ help = "Mark a signal report never-billable. Refuses if a billable PR run already exists (use a refund)."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("team_id", type=int, help="Team the report belongs to")+ parser.add_argument("report_id", type=str, help="SignalReport id (UUID)")+ parser.add_argument(+ "reason",+ type=str,+ choices=list(SignalReport.BillingExemptReason.values),+ help="Exemption reason (posthog_system is the generic ops value)",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ report = SignalReport.objects.filter(team_id=options["team_id"], id=options["report_id"]).first()+ if report is None:+ raise CommandError(f"Report {options['report_id']} not found for team {options['team_id']}")++ try:+ changed = mark_report_billing_exempt(report, options["reason"])+ except BillingExemptionError as e:+ raise CommandError(str(e))++ if not changed:+ self.stdout.write(+ self.style.WARNING(+ f"Report {report.id} is already billing-exempt ({report.billing_exempt_reason}); left unchanged."+ )+ )+ return+ self.stdout.write(+ self.style.SUCCESS(f"Report {report.id} marked billing-exempt ({report.billing_exempt_reason}).")+ )diff --git a/products/signals/backend/management/commands/seed_inbox_data.py b/products/signals/backend/management/commands/seed_inbox_data.pyindex bbc2f549c2a0..0252c06f243e 100644--- a/products/signals/backend/management/commands/seed_inbox_data.py+++ b/products/signals/backend/management/commands/seed_inbox_data.py@@ -7,6 +7,8 @@ each one persisted through the same `_persist_agentic_report_artefacts` path theMost reports also get a `tasks.Task` + `TaskRun` with a synthetic JSONL transcript written to objectstorage, so the inbox's inline run viewer renders a real-looking agent log without running a sandbox.Tasks/runs are created through the tasks facade (the product is isolated) — never by touching its ORM.+Runs are recorded via the production dual-write (`record_implementation_task`), so seeded reports are+billable-faithful; for the refund-path matrix (excluded/credited/exempt) use `seed_refund_test_data`.DEBUG only.@@ -26,18 +28,16 @@ from django.db import transactionfrom posthog.models import OrganizationMembership, Teamfrom products.signals.backend.artefact_schemas import (- SIGNALS_PRODUCT,- TASK_RUN_TYPE_IMPLEMENTATION,Commit,NoteArtefact,RelevantCommit,SuggestedReviewerEntry,SuggestedReviewers,- TaskRunArtefact,)-from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalReportRefundfrom products.signals.backend.report_generation.research import ReportResearchOutputfrom products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.task_run_artefacts import record_implementation_taskfrom products.signals.backend.temporal.agentic.report import _persist_agentic_report_artefactsfrom products.tasks.backend.facade import api as tasks_facade@@ -158,6 +158,8 @@ class Command(BaseCommand):return fixturesdef _clear_existing(self, team: Team) -> None:+ # Refunds RESTRICT report deletion; reseeding means a full reset.+ SignalReportRefund.objects.for_team(team.id).delete()deleted, _ = SignalReport.objects.filter(team=team).delete()self.stdout.write(self.style.WARNING(f"Deleted {deleted} existing signal report row(s) for team {team.id}"))@@ -301,14 +303,10 @@ class Command(BaseCommand):"output": {"pr_url": pr_url, "branch": branch},},)- SignalReportArtefact.add_log(- team_id=team.id,- report_id=str(report.id),- content=TaskRunArtefact(- task_id=task_id, run_id=run_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION- ),- attribution=ArtefactAttribution.from_task(task_id),- )+ # Production dual-write (`SignalReportTask` bridge row + `task_run` artefact) so seeded+ # reports are billable-faithful — the billing query is rooted on the bridge, and an+ # artefact alone makes the PR visible in the UI but not chargeable/refundable.+ record_implementation_task(team_id=team.id, report_id=str(report.id), task_id=task_id, run_id=run_id)# ── synthetic transcript ───────────────────────────────────────────────────────diff --git a/products/signals/backend/management/commands/seed_refund_test_data.py b/products/signals/backend/management/commands/seed_refund_test_data.pynew file mode 100644index 000000000000..8de1a88d42ab--- /dev/null+++ b/products/signals/backend/management/commands/seed_refund_test_data.py@@ -0,0 +1,198 @@+"""Local dev tool: seed *billable* Signals reports for exercising the PR refund flow.++`seed_inbox_data` gives the inbox rich-looking reports; this command gives it billable ones —+reports whose implementation run carries a GitHub PR URL plus the `SignalReportTask` bridge row+the billing query is rooted on, with run timestamps chosen to reach each refund path.++Creates five reports per invocation (a report can only ever be refunded once, so re-run freely):++1. PR run today → refund takes the `excluded` path (usage query skips the report)+2. PR run 4 days ago → refund takes the `credited` path (Celery → billing dispute endpoint)+3. PR run last month → out of the billing period: Refund renders disabled with the reason+4. billing-exempt, with PR → "Free" badge (health-check tooltip); refund hidden+5. no PR run yet → valid target for `manage.py exempt_signal_report_billing`++The refund endpoints are gated on the `signals-pr-refunds` feature flag; the full local setup+(flag, local billing service, verification queries) is in the "Testing refunds locally" section+of products/signals/ARCHITECTURE.md.++DEBUG only.++ python manage.py seed_refund_test_data --team-id 1+"""++from datetime import datetime, timedelta++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError+from django.db import transaction+from django.utils import timezone++from posthog.models import OrganizationMembership, Team++from products.signals.backend.billing import first_billable_pr_run+from products.signals.backend.models import SignalReport+from products.signals.backend.task_run_artefacts import record_implementation_task+from products.tasks.backend.facade import api as tasks_facade++_DEFAULT_REPOSITORY = "posthog/posthog"+++class Command(BaseCommand):+ help = "Seed billable Signals reports covering every refund/exemption path (DEBUG only)."++ def add_arguments(self, parser):+ parser.add_argument("--team-id", type=int, required=True, help="Team to seed reports for")+ parser.add_argument(+ "--user-id",+ type=int,+ default=None,+ help="User to attribute tasks to (default: first member of the team's organization)",+ )+ parser.add_argument(+ "--repository",+ type=str,+ default=_DEFAULT_REPOSITORY,+ help=f"owner/repo used in the seeded PR URLs (default: {_DEFAULT_REPOSITORY})",+ )++ def handle(self, *args, **options):+ if not settings.DEBUG:+ raise CommandError("This command can only be run with DEBUG=True")++ team = self._get_team(options["team_id"])+ user_id = self._resolve_user_id(team, options["user_id"])+ repository = options["repository"]+ now = timezone.now()+ stamp = now.strftime("%m%d-%H%M%S")+ # PR numbers only need to look distinct in the UI; derive from the clock.+ pr_base = int(now.timestamp()) % 900_000++ excluded = self._seed_billable_report(+ team,+ user_id,+ title=f"[{stamp}] Refund test: excluded path (PR today)",+ repository=repository,+ pr_number=pr_base + 1,+ )+ credited = self._seed_billable_report(+ team,+ user_id,+ title=f"[{stamp}] Refund test: credited path (PR 4 days ago)",+ repository=repository,+ pr_number=pr_base + 2,+ run_created_at=now - timedelta(days=4),+ )+ out_of_period = self._seed_billable_report(+ team,+ user_id,+ title=f"[{stamp}] Refund test: out of period (PR last month, Refund disabled)",+ repository=repository,+ pr_number=pr_base + 3,+ run_created_at=now - timedelta(days=35),+ )+ exempt = self._seed_billable_report(+ team,+ user_id,+ title=f"[{stamp}] Refund test: billing-exempt (Free badge, health check)",+ repository=repository,+ pr_number=pr_base + 4,+ exempt_reason=SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK,+ )+ no_pr = self._make_report(team, title=f"[{stamp}] Refund test: no PR yet (exemption target)")++ self.stdout.write(f"1. excluded-path report: {excluded.id}")+ self.stdout.write(f"2. credited-path report: {credited.id}")+ self.stdout.write(f"3. out-of-period report: {out_of_period.id}")+ self.stdout.write(f"4. exempt report: {exempt.id}")+ self.stdout.write(f"5. no-PR report: {no_pr.id}")+ self.stdout.write(f" try: python manage.py exempt_signal_report_billing {team.id} {no_pr.id} posthog_system")+ self.stdout.write(+ self.style.SUCCESS(f"Seeded 5 refund-test reports for team {team.id} — open the inbox's Ready list.")+ )++ def _seed_billable_report(+ self,+ team: Team,+ user_id: int,+ *,+ title: str,+ repository: str,+ pr_number: int,+ run_created_at: datetime | None = None,+ exempt_reason: str | None = None,+ ) -> SignalReport:+ report = self._make_report(team, title=title)+ created = tasks_facade.create_and_run_task(+ team=team,+ title=f"impl: {title}",+ description="Synthetic implementation task seeded for refund testing.",+ origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,+ user_id=user_id,+ repository=repository,+ create_pr=False,+ start_workflow=False,+ signal_report_id=str(report.id),+ internal=False,+ )+ run = created.latest_run+ if run is None:+ raise CommandError(f"Task creation for report {report.id} produced no run")+ task_id, run_id = str(created.task_id), str(run.id)++ # Production ordering: the bridge row (and any exemption) is recorded when the task starts,+ # before the run can ship a billable PR — the exemption freeze rule depends on this.+ with transaction.atomic():+ record_implementation_task(+ team_id=team.id,+ report_id=str(report.id),+ task_id=task_id,+ run_id=run_id,+ billing_exempt_reason=exempt_reason,+ )+ tasks_facade.update_task_run(+ run_id,+ task_id,+ team.id,+ validated_data={+ "status": "completed",+ "output": {"pr_url": f"https://github.com/{repository}/pull/{pr_number}"},+ },+ )+ if run_created_at is not None:+ tasks_facade.set_task_run_created_at_for_seeding(run_id, task_id, team.id, created_at=run_created_at)++ billable = first_billable_pr_run(report.id)+ if billable is None:+ raise CommandError(f"Report {report.id} is not billable after seeding — bridge/run wiring broke")+ self.stdout.write(f" · billable at {billable.created_at.isoformat()} ({billable.pr_url})")+ return report++ def _make_report(self, team: Team, *, title: str) -> SignalReport:+ return SignalReport.objects.create(+ team=team,+ status=SignalReport.Status.READY,+ signal_count=1,+ total_weight=1.0,+ title=title,+ summary="Seeded by seed_refund_test_data for refund-flow testing.",+ )++ def _get_team(self, team_id: int) -> Team:+ try:+ return Team.objects.select_related("organization").get(id=team_id)+ except Team.DoesNotExist:+ raise CommandError(f"Team {team_id} not found")++ def _resolve_user_id(self, team: Team, user_id: int | None) -> int:+ if user_id is not None:+ return user_id+ membership = (+ OrganizationMembership.objects.filter(organization_id=team.organization_id)+ .order_by("joined_at")+ .values_list("user_id", flat=True)+ .first()+ )+ if membership is None:+ raise CommandError(f"Team {team.id}'s organization has no members; pass --user-id explicitly")+ return membershipdiff --git a/products/signals/backend/migrations/0057_signalreportrefund.py b/products/signals/backend/migrations/0057_signalreportrefund.pynew file mode 100644index 000000000000..c2ef5dfc299c--- /dev/null+++ b/products/signals/backend/migrations/0057_signalreportrefund.py@@ -0,0 +1,104 @@+# Generated by Django 5.2.14 on 2026-07-13 14:06++import django.db.models.manager+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1251_alter_integration_kind"),+ ("signals", "0056_alter_signalreportartefact_type"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="SignalReportRefund",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "reason",+ models.CharField(+ choices=[+ ("pr_incorrect", "PR incorrect"),+ ("pr_not_useful", "PR not useful"),+ ("duplicate", "Duplicate"),+ ("other", "Other"),+ ],+ max_length=20,+ ),+ ),+ ("note", models.TextField(blank=True)),+ (+ "billing_path",+ models.CharField(+ choices=[("excluded", "Excluded"), ("credited", "Credited")],+ max_length=10,+ ),+ ),+ ("credits", models.IntegerField()),+ ("pr_url", models.TextField()),+ ("pr_run_created_at", models.DateTimeField()),+ (+ "credit_amount_usd",+ models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True),+ ),+ ("billing_synced_at", models.DateTimeField(blank=True, null=True)),+ ("billing_sync_error", models.TextField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "report",+ models.OneToOneField(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="refund",+ to="signals.signalreport",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "verbose_name": "Signal report refund",+ "verbose_name_plural": "Signal report refunds",+ "default_manager_name": "all_teams",+ "indexes": [+ models.Index(+ fields=["team", "billing_path", "pr_run_created_at"],+ name="signals_refund_path_idx",+ )+ ],+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ ]diff --git a/products/signals/backend/migrations/0058_signalreport_billing_exempt_reason.py b/products/signals/backend/migrations/0058_signalreport_billing_exempt_reason.pynew file mode 100644index 000000000000..1f31a12698c4--- /dev/null+++ b/products/signals/backend/migrations/0058_signalreport_billing_exempt_reason.py@@ -0,0 +1,26 @@+# Generated by Django 5.2.14 on 2026-07-13 14:06++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0057_signalreportrefund"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalreport",+ name="billing_exempt_reason",+ field=models.CharField(+ blank=True,+ choices=[+ ("posthog_health_check", "PostHog health check"),+ ("posthog_onboarding", "PostHog onboarding"),+ ("posthog_system", "PostHog system"),+ ],+ max_length=30,+ null=True,+ ),+ ),+ ]diff --git a/products/signals/backend/migrations/0059_alter_signalreportrefund_report.py b/products/signals/backend/migrations/0059_alter_signalreportrefund_report.pynew file mode 100644index 000000000000..8b5f94712fce--- /dev/null+++ b/products/signals/backend/migrations/0059_alter_signalreportrefund_report.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-07-14 10:40++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0058_signalreport_billing_exempt_reason"),+ ]++ operations = [+ migrations.AlterField(+ model_name="signalreportrefund",+ name="report",+ field=models.OneToOneField(+ on_delete=django.db.models.deletion.RESTRICT,+ related_name="refund",+ to="signals.signalreport",+ ),+ ),+ ]diff --git a/products/signals/backend/migrations/0060_signalreportrefund_period_bounds.py b/products/signals/backend/migrations/0060_signalreportrefund_period_bounds.pynew file mode 100644index 000000000000..44afb95b17e2--- /dev/null+++ b/products/signals/backend/migrations/0060_signalreportrefund_period_bounds.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-07-14 15:30++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0059_alter_signalreportrefund_report"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalreportrefund",+ name="period_start",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="signalreportrefund",+ name="period_end",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex 22a42af119e2..38a72ccd4072 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0056_alter_signalreportartefact_type+0060_signalreportrefund_period_boundsdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex ce996e15659e..613e9b1c08b1 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -187,8 +187,18 @@ class SignalReport(UUIDModel):DELETED = "deleted"SUPPRESSED = "suppressed"+ class BillingExemptReason(models.TextChoices):+ POSTHOG_HEALTH_CHECK = "posthog_health_check", "PostHog health check"+ POSTHOG_ONBOARDING = "posthog_onboarding", "PostHog onboarding"+ POSTHOG_SYSTEM = "posthog_system", "PostHog system"+team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)status = models.CharField(max_length=20, choices=Status, default=Status.POTENTIAL)+ # System billing exemption: non-null means this report's implementation PRs must never be+ # charged (PostHog-system origins, e.g. health-check scout findings). Prospective-only —+ # set via `billing.mark_report_billing_exempt` while no billable PR run exists, and never+ # flipped afterwards, so no usage report can observe the value changing. Null = billable.+ billing_exempt_reason = models.CharField(max_length=30, choices=BillingExemptReason, null=True, blank=True)# The status held immediately before the report was suppressed (archived). Lets "restore"# return the report to where it was instead of always dropping it back to POTENTIAL.# Null for reports that were never suppressed (and cleared again on restore).@@ -943,6 +953,80 @@ class SignalReportTask(UUIDModel):]+class SignalReportRefund(TeamScopedRootMixin, UUIDModel):+ """One refund per report, ever — the user-facing "Refund" on a billed implementation PR.++ The row freezes everything billing-relevant at refund time: the `billing_path` (decided once+ by the UTC-day rule in `billing.py`, never recomputed), the flat `credits` charge, the+ `pr_url` / `pr_run_created_at` snapshots that make eligibility auditable and the quota offset+ a pure indexed filter on this table, and the billing period bounds the refund was accepted+ in, which the credited-path sync reports to billing. The `report` OneToOne is the concurrency+ backstop — a racing second refund hits its unique constraint.+ """++ class Reason(models.TextChoices):+ PR_INCORRECT = "pr_incorrect", "PR incorrect"+ PR_NOT_USEFUL = "pr_not_useful", "PR not useful"+ DUPLICATE = "duplicate", "Duplicate"+ OTHER = "other", "Other"++ class BillingPath(models.TextChoices):+ # Refund landed on the same UTC day as the first billable PR run: the usage query simply+ # excludes the report, so billing never learns it existed.+ EXCLUDED = "excluded"+ # Refund landed later in the billing period: usage stays truthful and the billing service+ # issues a Stripe customer-balance credit via the dispute endpoint.+ CREDITED = "credited"++ # `objects` (TeamScopedManager) inherited from TeamScopedRootMixin stays fail-closed for+ # explicit user code. `all_teams` is the unscoped sibling for Django framework internals+ # (admin changelist queryset, related-object access, prefetch_related) that must not+ # filter by team. `default_manager_name` routes `_default_manager` / `_base_manager`+ # there. Same pattern as ProductTeamModel — duplicated here because TeamScopedRootMixin+ # doesn't bake it in (most callers don't need it).+ all_teams = models.Manager() # noqa: DJ012++ # FKs to the hot posthog_team / posthog_user tables use db_constraint=False so creating this+ # table takes no lock on those parents (app-level enforcement only).+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ # RESTRICT: hard-deleting a report must never silently destroy this financial record (it drives+ # the quota offset and refund audit). Team deletion still cascades in via the team FK above.+ report = models.OneToOneField(SignalReport, on_delete=models.RESTRICT, related_name="refund")+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"+ )+ # Required — the future step-2 refund judge consumes these.+ reason = models.CharField(max_length=20, choices=Reason)+ note = models.TextField(blank=True)+ billing_path = models.CharField(max_length=10, choices=BillingPath)+ # Snapshot of SIGNALS_CREDITS_PER_REPORT_WITH_PR at refund time.+ credits = models.IntegerField()+ pr_url = models.TextField()+ # The first billable PR run's created_at — the billable moment this refund reverses.+ pr_run_created_at = models.DateTimeField()+ # The org's billing period [start, end) the refund was accepted in, frozen at creation. The+ # credited-path sync sends these bounds so billing can compute the credit against the accepted+ # period even when the sync lands after rollover — recomputing bounds at sync time is exactly+ # the drift that loses the credit. Null only on rows created before these fields existed.+ period_start = models.DateTimeField(null=True, blank=True)+ period_end = models.DateTimeField(null=True, blank=True)+ # Credited path only: what billing actually credited, written back by the sync task.+ # Null until billing responds ($0 is a legitimate synced outcome, e.g. free tier).+ credit_amount_usd = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)+ billing_synced_at = models.DateTimeField(null=True, blank=True)+ billing_sync_error = models.TextField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ verbose_name = "Signal report refund"+ verbose_name_plural = "Signal report refunds"+ default_manager_name = "all_teams"+ indexes = [+ # The quota offset sums credited refunds per org billing period; this makes it a seek.+ models.Index(fields=["team", "billing_path", "pr_run_created_at"], name="signals_refund_path_idx"),+ ]++# ── Signals scout (headless cross-source explorer) ──────────────────────────────## Three tables back the v1 Signals scout:diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 8ac093c8eade..554019ffe90d 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -13,6 +13,7 @@ from posthog.models import Userfrom posthog.temporal.common.client import sync_connectfrom products.signals.backend import contracts+from products.signals.backend.billing import REFUND_INELIGIBILITY_REASONS, refund_ineligibility_reasonfrom products.signals.backend.enums import SignalSourceProduct, SignalSourceTypefrom .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES@@ -20,6 +21,7 @@ from .models import (AutonomyPriority,SignalReport,SignalReportArtefact,+ SignalReportRefund,SignalSourceConfig,SignalTeamConfig,SignalUserAutonomyConfig,@@ -273,8 +275,66 @@ class SignalUserAutonomyConfigCreateSerializer(serializers.Serializer):)+class SignalReportRefundSerializer(serializers.ModelSerializer):+ billing_synced = serializers.SerializerMethodField(+ help_text=(+ "Whether the billing service has acknowledged this refund. Always relevant for the "+ "credited path (the Stripe credit is issued asynchronously); excluded-path refunds "+ "need no billing sync and report false."+ ),+ )++ class Meta:+ model = SignalReportRefund+ fields = [+ "id",+ "reason",+ "note",+ "billing_path",+ "credits",+ "pr_url",+ "pr_run_created_at",+ "credit_amount_usd",+ "billing_synced",+ "created_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "reason": {"help_text": "Why the user refunded this PR (feeds the refund review)."},+ "note": {"help_text": "Optional free-form note captured with the refund."},+ "billing_path": {+ "help_text": (+ "How the refund was executed, frozen at refund time: 'excluded' (same UTC day as "+ "the billable PR run — the report never reaches billing) or 'credited' (billing "+ "issues a Stripe customer-balance credit)."+ )+ },+ "credits": {"help_text": "Signals credits refunded (flat per-PR charge snapshot; 1 credit = $0.01)."},+ "pr_url": {"help_text": "The refunded implementation PR's GitHub URL, snapshotted at refund time."},+ "pr_run_created_at": {+ "help_text": "When the first billable PR run was created — the charge this reverses."+ },+ "credit_amount_usd": {+ "help_text": (+ "USD amount the billing service credited (credited path only). Null until the sync "+ "completes; '0.00' is a legitimate outcome (e.g. the PR was inside the free tier)."+ )+ },+ "created_at": {"help_text": "When the refund was created."},+ }++ def get_billing_synced(self, obj: SignalReportRefund) -> bool:+ return obj.billing_synced_at is not None++class SignalReportSerializer(serializers.ModelSerializer):artefact_count = serializers.IntegerField(read_only=True)+ refund_ineligibility_reason = serializers.SerializerMethodField(+ help_text=(+ "Why refunding this report's PR would be rejected right now, or null when a refund "+ "would be accepted (see the field's schema for the reason values)."+ ),+ )priority = serializers.SerializerMethodField(help_text="P0–P4 from the latest priority judgment artefact (when present).",)@@ -300,6 +360,9 @@ class SignalReportSerializer(serializers.ModelSerializer):implementation_pr_url = serializers.SerializerMethodField(help_text="PR URL from the latest implementation task run, if available.",)+ refund = serializers.SerializerMethodField(+ help_text="The report's PR refund, when one exists. One refund per report, ever.",+ )class Meta:model = SignalReport@@ -323,8 +386,20 @@ class SignalReportSerializer(serializers.ModelSerializer):"source_products","scout_name","implementation_pr_url",+ "refund",+ "refund_ineligibility_reason",+ "billing_exempt_reason",]read_only_fields = fields+ extra_kwargs = {+ "billing_exempt_reason": {+ "help_text": (+ "Non-null when this report is system-marked never-billable (PostHog-system origin, "+ "e.g. a health-check scout finding) — its implementation PRs are free and cannot be "+ "refunded because nothing was charged."+ )+ },+ }def _get_actionability_artefact_data(self, obj: SignalReport) -> dict | None:prefetched = getattr(obj, "prefetched_actionability_artefacts", None)@@ -427,6 +502,40 @@ class SignalReportSerializer(serializers.ModelSerializer):value = getattr(obj, "implementation_pr_url", None)return value if isinstance(value, str) else None+ @extend_schema_field(SignalReportRefundSerializer(allow_null=True))+ def get_refund(self, obj: SignalReport) -> dict | None:+ # Reverse OneToOne: RelatedObjectDoesNotExist subclasses AttributeError, so getattr+ # degrades to None for unrefunded reports. The viewset select_related()s the relation.+ refund = getattr(obj, "refund", None)+ if refund is None:+ return None+ return SignalReportRefundSerializer(refund).data++ @extend_schema_field(+ serializers.ChoiceField(+ choices=list(REFUND_INELIGIBILITY_REASONS),+ allow_null=True,+ help_text=(+ "Why refunding this report's PR would be rejected right now, or null when a refund "+ "would be accepted. Shares the refund endpoint's eligibility decision, so the UI can "+ "disable the Refund action instead of offering a request that would 400. One of: "+ "already_refunded, billing_exempt, no_billable_pr, out_of_period."+ ),+ )+ )+ def get_refund_ineligibility_reason(self, obj: SignalReport) -> str | None:+ period = self.context.get("billing_period_bounds")+ # Degrades to null (eligible) outside the reports viewset, where neither the period+ # context nor the billable-moment annotation exists — the refund endpoint re-enforces.+ if period is None:+ return None+ return refund_ineligibility_reason(+ has_refund=getattr(obj, "refund", None) is not None,+ billing_exempt=bool(obj.billing_exempt_reason),+ billable_run_at=getattr(obj, "first_billable_pr_run_at", None),+ period=period,+ )+# ── Report `signals` action ─────────────────────────────────────────────────────#diff --git a/products/signals/backend/signal_metadata.py b/products/signals/backend/signal_metadata.pynew file mode 100644index 000000000000..1d1c60e335f4--- /dev/null+++ b/products/signals/backend/signal_metadata.py@@ -0,0 +1,105 @@+"""Per-report signal metadata read off ClickHouse, outside the temporal package.++Signals live as embedding documents in ClickHouse; this module answers "what backs this+report" for synchronous callers (the serializer list view, the auto-start analytics capture)+without importing `products.signals.backend.temporal` — whose `__init__` eagerly loads the+agentic workflow modules, which import `auto_start`, which needs this query: keeping it here+keeps that import graph acyclic.+"""++from dataclasses import dataclass++from posthog.schema import EmbeddingModelName++from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.models import Team++# The embedding model whose document rows constitute the signal store; every signals+# ClickHouse query filters on it.+EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_SMALL_1536+++@dataclass(frozen=True)+class ReportSignalMeta:+ """Per-report signal metadata read off ClickHouse for the inbox list/detail views."""++ source_products: list[str]+ # Raw skill_name slug of the authoring scout (e.g. "signals-scout-error-tracking"), when the+ # report's backing signals carry one. None for pipeline reports and reports emitted before the+ # scout stamped skill_name onto its signals.+ scout_name: str | None+++def fetch_source_products_for_reports(team: Team, report_ids: list[str]) -> dict[str, ReportSignalMeta]:+ """Return a mapping of report_id -> `ReportSignalMeta` (distinct source_products + authoring scout).++ Only includes non-deleted signals. Source products are returned in sorted order. `scout_name` is+ any non-empty `extra.skill_name` on the report's signals (all scout-authored signals of a report+ share one), or None.++ Bounds the argMax dedup to documents that ever carried one of these report_ids, instead+ of deduping the team's whole signal history. The unbounded dedup's memory grows with the+ team's total signal count; the candidate-bounded form keeps it proportional to the signals+ in the requested page's reports, which is what flattens the tail on signal-heavy teams.+ The report_id filter stays AFTER the argMax so "latest version wins" holds: a signal that+ was re-grouped to a different report is matched by the candidate scan (it once carried this+ report_id) but excluded by the outer filter (its latest metadata points elsewhere) — the+ same correctness trap fetch_report_ids_for_source_ids documents.+ """+ if not report_ids:+ return {}++ ch_query = """+ SELECT+ report_id,+ arraySort(groupUniqArray(source_product)) as source_products,+ anyIf(skill_name, skill_name != '') as scout_name+ FROM (+ SELECT+ JSONExtractString(metadata, 'report_id') as report_id,+ JSONExtractBool(metadata, 'deleted') as is_deleted,+ JSONExtractString(metadata, 'source_product') as source_product,+ JSONExtractString(metadata, 'extra', 'skill_name') as skill_name+ FROM (+ SELECT argMax(metadata, inserted_at) as metadata+ FROM document_embeddings+ WHERE model_name = {model_name}+ AND product = 'signals'+ AND document_type = 'signal'+ AND document_id IN (+ SELECT DISTINCT document_id+ FROM document_embeddings+ WHERE model_name = {model_name}+ AND product = 'signals'+ AND document_type = 'signal'+ AND JSONExtractString(metadata, 'report_id') IN ({report_ids})+ )+ GROUP BY document_id+ )+ )+ WHERE NOT is_deleted+ AND report_id != ''+ AND report_id IN ({report_ids})+ AND source_product != ''+ GROUP BY report_id+ """++ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)+ result = execute_hogql_query(+ query_type="SignalsFetchSourceProductsForReports",+ query=ch_query,+ team=team,+ placeholders={+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),+ "report_ids": ast.Tuple(exprs=[ast.Constant(value=rid) for rid in report_ids]),+ },+ )++ return {+ row[0]: ReportSignalMeta(source_products=row[1], scout_name=(row[2] or None))+ for row in (result.results or [])+ if row[0]+ }diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.pyindex 812ce71fbf2f..31d68089241f 100644--- a/products/signals/backend/task_run_artefacts.py+++ b/products/signals/backend/task_run_artefacts.py@@ -20,6 +20,7 @@ from products.signals.backend.artefact_schemas import (TASK_RUN_TYPE_RESEARCH,TaskRunArtefact,)+from products.signals.backend.billing import mark_report_billing_exemptfrom products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalReportTask# The task-run vocabulary lives in `artefact_schemas` (a leaf module the model layer can import@@ -94,7 +95,7 @@ def signals_task_ids(*, report_id: str, type: str) -> list[str]:def record_implementation_task(- *, team_id: int, report_id: str, task_id: str, run_id: str | None = None+ *, team_id: int, report_id: str, task_id: str, run_id: str | None = None, billing_exempt_reason: str | None = None) -> SignalReportArtefact:"""Record a started implementation task as BOTH the legacy `SignalReportTask` gate row and the`task_run` work-log artefact.@@ -105,7 +106,16 @@ def record_implementation_task(`backfill_task_run_artefacts` has converted every legacy row, the gate can switch to theartefact log and `SignalReportTask` can be dropped. Call inside the transaction that createdthe task. Shared by auto-start and the manual start-task API.++ `billing_exempt_reason` lets a caller that knows its origin is PostHog-system declare the+ report never-billable in the same transaction that records the task — before the run can ship+ a billable PR. Enforced by the prospective-only freeze rule (`billing.mark_report_billing_exempt`+ raises once a billable PR run exists). Auto-start stamps its exemption itself under its row+ lock and does not pass this."""+ if billing_exempt_reason:+ report = SignalReport.objects.select_for_update().get(id=report_id, team_id=team_id)+ mark_report_billing_exempt(report, billing_exempt_reason)SignalReportTask.objects.get_or_create(team_id=team_id,report_id=report_id,diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex b115778c4bf9..e713e14eaecc 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -1,8 +1,45 @@+from datetime import timedelta+from decimal import Decimal++from django.utils import timezone++import structlogfrom celery import shared_task+from posthog.cloud_utils import get_cached_instance_license+from posthog.event_usage import groups+from posthog.exceptions_capture import capture_exceptionfrom posthog.models.scoping import with_team_scope+from posthog.ph_client import ph_scoped_capture+from posthog.scoping_audit import skip_team_scope_audit+from products.signals.backend.billing import current_billing_period_boundsfrom products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report+from products.signals.backend.models import SignalReportRefund++logger = structlog.get_logger(__name__)++# Bounded exponential backoff: 2m, 4m, 8m, ... capped at 1h, 8 retries ≈ 5h total. Deliberately+# NOT unbounded — a hard failure should land with the sweeper (and its 7-day horizon) rather+# than retry forever. Rollover itself is survivable: the payload reports the period bounds+# frozen on the refund row, and billing credits against that period as long as it is still the+# customer's immediately-previous one.+_REFUND_SYNC_MAX_RETRIES = 8+_REFUND_SYNC_RETRY_BASE_SECONDS = 120+_REFUND_SYNC_RETRY_MAX_SECONDS = 3600++# Sweeper horizon: stop re-enqueueing unsynced credited refunds after 7 days. Anything older is+# an operational problem surfaced by the failure analytics event, handled manually (a billing+# admin creates the credit with idempotency key `signals_pr_dispute:{billing_customer_id}:{refund_id}`;+# the row then syncs as already_processed on any later attempt).+_REFUND_SYNC_SWEEP_MAX_AGE = timedelta(days=7)++# Billing answered a handled $0 because it could no longer credit the period the refund was+# accepted in — the sync outran billing's late-credit horizon (the frozen period is no longer+# the customer's current or immediately-previous one), or the row predates the frozen period+# bounds. Terminal for automation: retrying recomputes the same $0 (the frozen period only gets+# older), so the sweeper skips these rows and recovery is the documented manual credit path.+_OUT_OF_PERIOD_SYNC_ERROR = "billing: refund period no longer creditable at sync time; credit needs manual recovery"@shared_task(@@ -13,3 +50,170 @@ from products.signals.backend.implementation_pr import PrCloseReason, close_impl@with_team_scope()def close_dismissed_report_pr(report_id: str, team_id: int, reason: PrCloseReason = "suppressed") -> None:close_implementation_pr_for_report(team_id, report_id, reason=reason)+++def _capture_refund_sync_event(refund: SignalReportRefund, event: str, extra: dict[str, object]) -> None:+ organization = refund.team.organization+ with ph_scoped_capture() as capture:+ capture(+ distinct_id=str(organization.id),+ event=event,+ properties={+ "team_id": refund.team_id,+ "organization_id": str(organization.id),+ "report_id": str(refund.report_id),+ "refund_id": str(refund.id),+ "credits": refund.credits,+ **extra,+ },+ groups=groups(organization=organization),+ )+++@shared_task(+ name="products.signals.backend.tasks.sync_signals_refund_credit",+ ignore_result=True,+ bind=True,+ max_retries=_REFUND_SYNC_MAX_RETRIES,+)+@skip_team_scope_audit+def sync_signals_refund_credit(self, refund_id: str) -> None:+ """Report a credited-path refund to the billing dispute endpoint and record the outcome.++ Safe to re-deliver at any time (double-enqueue, sweeper overlap, manual re-run): billing is+ idempotent on `refund_id`, and an already-synced row returns immediately. User experience is+ unaffected while this lags — archive + badge + freed quota slot all happened at refund time;+ only the invoice credit waits.+ """+ from ee.billing.billing_manager import (+ BillingManager, # noqa: PLC0415 — keeps the ee layer off the products import path (precedent: posthog/tasks/sync_billing.py)+ )++ refund = (+ # nosemgrep: idor-lookup-without-team (system Celery task keyed by refund id from our own enqueue/sweeper, no user input; unscoped is the sanctioned cross-team access)+ SignalReportRefund.objects.unscoped()+ .select_related("team__organization")+ .filter(id=refund_id, billing_path=SignalReportRefund.BillingPath.CREDITED)+ .first()+ )+ if refund is None:+ logger.warning("signals refund credit sync: no credited refund found", refund_id=refund_id)+ return+ if refund.billing_synced_at is not None:+ return++ organization = refund.team.organization+ # Report the period bounds frozen at refund acceptance, so billing credits against the+ # period the refund was accepted in even when this sync lands after rollover — recomputing+ # bounds here is exactly the drift that loses the credit. The fallback covers rows created+ # before the bounds were snapshotted.+ if refund.period_start is not None and refund.period_end is not None:+ period_start, period_end = refund.period_start, refund.period_end+ else:+ period_start, period_end = current_billing_period_bounds(organization)+ payload = {+ "refund_id": str(refund.id),+ "credits": refund.credits,+ "metadata": {+ "team_id": refund.team_id,+ "report_id": str(refund.report_id),+ "pr_url": refund.pr_url,+ "pr_run_created_at": refund.pr_run_created_at.isoformat(),+ "period_start": period_start.isoformat(),+ "period_end": period_end.isoformat(),+ },+ }++ try:+ license = get_cached_instance_license()+ response = BillingManager(license, None).dispute_signals_pr(organization, payload)+ credit_amount_usd = Decimal(str(response["credit_amount_usd"]))+ except Exception as exc:+ if self.request.retries < _REFUND_SYNC_MAX_RETRIES:+ countdown = min(_REFUND_SYNC_RETRY_BASE_SECONDS * (2**self.request.retries), _REFUND_SYNC_RETRY_MAX_SECONDS)+ raise self.retry(exc=exc, countdown=countdown)+ # Terminal for this delivery — record the error for the weekly review; the hourly sweeper+ # keeps re-enqueueing the row for up to 7 days, after which recovery is operational. The+ # conditional update mirrors the success-path claim below: never stamp an error (or emit+ # the failed event) onto a row a concurrent delivery already synced.+ recorded = (+ # nosemgrep: idor-lookup-without-team (id comes from the sanctioned unscoped lookup above; system task, no user input)+ SignalReportRefund.objects.unscoped()+ .filter(id=refund.id, billing_synced_at__isnull=True)+ .update(billing_sync_error=str(exc)[:4000])+ )+ if recorded:+ capture_exception(exc, {"refund_id": str(refund.id), "team_id": refund.team_id})+ _capture_refund_sync_event(refund, "signals_pr_refund_credit_failed", {"error": str(exc)[:1000]})+ return++ if response.get("zero_reason") == "out_of_period":+ # The $0 means billing could no longer credit the frozen refund period (see+ # _OUT_OF_PERIOD_SYNC_ERROR), not that the refund was legitimately free. Record a sync+ # error instead of a synced $0 so the row surfaces for manual recovery.+ recorded = (+ # nosemgrep: idor-lookup-without-team (id comes from the sanctioned unscoped lookup above; system task, no user input)+ SignalReportRefund.objects.unscoped()+ .filter(id=refund.id, billing_synced_at__isnull=True)+ .update(billing_sync_error=_OUT_OF_PERIOD_SYNC_ERROR)+ )+ if recorded:+ capture_exception(+ Exception("signals refund credit lost to billing period rollover"),+ {"refund_id": str(refund.id), "team_id": refund.team_id},+ )+ _capture_refund_sync_event(refund, "signals_pr_refund_credit_failed", {"error": _OUT_OF_PERIOD_SYNC_ERROR})+ return++ # Atomic claim: the on-commit enqueue and the hourly sweeper can race two deliveries for the+ # same refund past the billing_synced_at gate above while the billing call is in flight+ # (billing stays idempotent, so the credit itself is issued once). Only the delivery that+ # flips the row records the sync and emits the issued event, keeping the weekly-review+ # analytics single-counted.+ claimed = (+ # nosemgrep: idor-lookup-without-team (id comes from the sanctioned unscoped lookup above; system task, no user input)+ SignalReportRefund.objects.unscoped()+ .filter(id=refund.id, billing_synced_at__isnull=True)+ .update(credit_amount_usd=credit_amount_usd, billing_synced_at=timezone.now(), billing_sync_error=None)+ )+ if not claimed:+ return+ _capture_refund_sync_event(+ refund,+ "signals_pr_refund_credit_issued",+ {+ "credit_amount_usd": str(credit_amount_usd),+ "already_processed": bool(response.get("already_processed")),+ },+ )+++@shared_task(+ name="products.signals.backend.tasks.sync_pending_signals_refund_credits",+ ignore_result=True,+ max_retries=0,+)+@skip_team_scope_audit+def sync_pending_signals_refund_credits() -> None:+ """Hourly sweeper: re-enqueue credited refunds whose billing sync hasn't landed yet.++ Catches deliveries lost to worker crashes / deploys and rows whose bounded retries were+ exhausted while billing was down. Only rows younger than the sweep horizon are retried;+ re-enqueueing an already-synced row is a no-op in the task itself.+ """+ cutoff = timezone.now() - _REFUND_SYNC_SWEEP_MAX_AGE+ pending_ids = list(+ SignalReportRefund.objects.unscoped()+ .filter(+ billing_path=SignalReportRefund.BillingPath.CREDITED,+ billing_synced_at__isnull=True,+ created_at__gte=cutoff,+ )+ # Horizon-lost credits are terminal for automation — replaying returns the same $0.+ .exclude(billing_sync_error=_OUT_OF_PERIOD_SYNC_ERROR)+ .values_list("id", flat=True)+ )+ for refund_id in pending_ids:+ sync_signals_refund_credit.delay(str(refund_id))+ if pending_ids:+ logger.info("signals refund credit sweeper re-enqueued pending refunds", count=len(pending_ids))diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex 23226f36c1dc..a709d281316e 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -29,12 +29,13 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections+from products.signals.backend.billing import BILLING_EXEMPT_SOURCE_PRODUCTSfrom products.signals.backend.models import SignalReport+from products.signals.backend.signal_metadata import EMBEDDING_MODELfrom products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.drop_telemetry import capture_signal_droppedfrom products.signals.backend.temporal.llm import MAX_QUERY_TOKENS, call_llm, truncate_query_to_token_limitfrom products.signals.backend.temporal.signal_queries import (- EMBEDDING_MODEL,FetchSignalsForReportInput,FetchSignalsForReportOutput,FetchSignalTypeExamplesInput,@@ -739,6 +740,10 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Assignal_count=1,title=match_result.title,summary=match_result.summary,+ # A report born from a PostHog-system signal (e.g. health checks) must never+ # bill the customer. Only this founding signal decides: signals that join the+ # report later (the branch above) leave the exemption unchanged either way.+ billing_exempt_reason=BILLING_EXEMPT_SOURCE_PRODUCTS.get(input.source_product),)# Promotion rules by status:diff --git a/products/signals/backend/temporal/reingestion.py b/products/signals/backend/temporal/reingestion.pyindex 04cc943dfa3c..b1df3ae3ca00 100644--- a/products/signals/backend/temporal/reingestion.py+++ b/products/signals/backend/temporal/reingestion.py@@ -21,11 +21,11 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.facade.api import emit_signalfrom products.signals.backend.models import SignalReport, SignalReportArtefact+from products.signals.backend.signal_metadata import EMBEDDING_MODELfrom products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retryfrom products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflowfrom products.signals.backend.temporal.signal_queries import (_DEDUPED_SIGNALS_SUBQUERY,- EMBEDDING_MODEL,FetchSignalsForReportInput,FetchSignalsForReportOutput,WaitForClickHouseInput,diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex 9f7076d5cc4b..f209be0b9ece 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -18,13 +18,13 @@ from posthog.models import Teamfrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections+from products.signals.backend.signal_metadata import EMBEDDING_MODELfrom products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retryfrom products.signals.backend.temporal.types import SignalCandidate, SignalData, SignalTypeExamplelogger = structlog.get_logger(__name__)-EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_SMALL_1536WAIT_POLL_INTERVAL_SECONDS = 10@@ -603,94 +603,6 @@ def fetch_report_ids_for_source_products(team: Team, source_products: list[str])return {row[0] for row in (result.results or []) if row[0]}-# ----------------------------------------------------------------------------# fetch_source_products_for_reports — synchronous, for the serializer list view-# ------------------------------------------------------------------------------@dataclass(frozen=True)-class ReportSignalMeta:- """Per-report signal metadata read off ClickHouse for the inbox list/detail views."""-- source_products: list[str]- # Raw skill_name slug of the authoring scout (e.g. "signals-scout-error-tracking"), when the- # report's backing signals carry one. None for pipeline reports and reports emitted before the- # scout stamped skill_name onto its signals.- scout_name: str | None---def fetch_source_products_for_reports(team: Team, report_ids: list[str]) -> dict[str, ReportSignalMeta]:- """Return a mapping of report_id -> `ReportSignalMeta` (distinct source_products + authoring scout).-- Only includes non-deleted signals. Source products are returned in sorted order. `scout_name` is- any non-empty `extra.skill_name` on the report's signals (all scout-authored signals of a report- share one), or None.-- Bounds the argMax dedup to documents that ever carried one of these report_ids, instead- of deduping the team's whole signal history. The unbounded dedup's memory grows with the- team's total signal count; the candidate-bounded form keeps it proportional to the signals- in the requested page's reports, which is what flattens the tail on signal-heavy teams.- The report_id filter stays AFTER the argMax so "latest version wins" holds: a signal that- was re-grouped to a different report is matched by the candidate scan (it once carried this- report_id) but excluded by the outer filter (its latest metadata points elsewhere) — the- same correctness trap fetch_report_ids_for_source_ids documents.- """- if not report_ids:- return {}-- ch_query = """- SELECT- report_id,- arraySort(groupUniqArray(source_product)) as source_products,- anyIf(skill_name, skill_name != '') as scout_name- FROM (- SELECT- JSONExtractString(metadata, 'report_id') as report_id,- JSONExtractBool(metadata, 'deleted') as is_deleted,- JSONExtractString(metadata, 'source_product') as source_product,- JSONExtractString(metadata, 'extra', 'skill_name') as skill_name- FROM (- SELECT argMax(metadata, inserted_at) as metadata- FROM document_embeddings- WHERE model_name = {model_name}- AND product = 'signals'- AND document_type = 'signal'- AND document_id IN (- SELECT DISTINCT document_id- FROM document_embeddings- WHERE model_name = {model_name}- AND product = 'signals'- AND document_type = 'signal'- AND JSONExtractString(metadata, 'report_id') IN ({report_ids})- )- GROUP BY document_id- )- )- WHERE NOT is_deleted- AND report_id != ''- AND report_id IN ({report_ids})- AND source_product != ''- GROUP BY report_id- """-- tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)- result = execute_hogql_query(- query_type="SignalsFetchSourceProductsForReports",- query=ch_query,- team=team,- placeholders={- "model_name": ast.Constant(value=EMBEDDING_MODEL.value),- "report_ids": ast.Tuple(exprs=[ast.Constant(value=rid) for rid in report_ids]),- },- )-- return {- row[0]: ReportSignalMeta(source_products=row[1], scout_name=(row[2] or None))- for row in (result.results or [])- if row[0]- }--# ---------------------------------------------------------------------------# fetch_report_ids_for_source_ids — synchronous, for the scout reverse lookup# ---------------------------------------------------------------------------diff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.pyindex 17c971bde23b..3e96c9b1814c 100644--- a/products/signals/backend/test/test_assign_and_emit_signal.py+++ b/products/signals/backend/test/test_assign_and_emit_signal.py@@ -84,13 +84,14 @@ def _build_input(team_id: int,match_result: ExistingReportMatch | NewReportMatch,weight: float = 0.5,+ source_product: str = "conversations",) -> AssignAndEmitSignalInput:return AssignAndEmitSignalInput(team_id=team_id,signal_id=str(uuid.uuid4()),description="A test signal description",weight=weight,- source_product="conversations",+ source_product=source_product,source_type="ticket",source_id=f"src-{uuid.uuid4()}",extra={},@@ -134,6 +135,51 @@ async def test_new_match_creates_and_immediately_promotes_when_above_threshold(aassert report.promoted_at is not None+# ---------------------------------------------------------------------------+# Billing exemption: PostHog-system signal sources+# ---------------------------------------------------------------------------+++ "source_product,expected_reason",+ [+ ("health_checks", SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK),+ ("conversations", None),+ ],+)+async def test_new_report_billing_exemption_follows_source_product(ateam, source_product, expected_reason):+ """A report formed from a PostHog-system signal (health checks) is stamped never-billable at+ creation; reports from customer sources stay billable."""+ input_ = _build_input(ateam.id, _new_match(), source_product=source_product)++ result = await assign_and_emit_signal_activity(input_)++ report = await database_sync_to_async(SignalReport.objects.get)(id=result.report_id)+ assert report.billing_exempt_reason == expected_reason+++async def test_exempt_source_signal_joining_existing_report_never_flips_it(ateam):+ """The exemption is frozen at formation: a health-check signal grouped into a customer-origin+ report must not make that report free (and would silently exempt paid work if it did)."""+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.POTENTIAL,+ total_weight=0.2,+ signal_count=1,+ )+ input_ = _build_input(ateam.id, _existing_match(str(report.id)), source_product="health_checks")++ await assign_and_emit_signal_activity(input_)++ refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)+ assert refreshed.billing_exempt_reason is None+ assert refreshed.signal_count == 2++# ---------------------------------------------------------------------------# Happy path: existing POTENTIAL crossing thresholds# ---------------------------------------------------------------------------diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.pyindex 1b26d187c3c2..35ff5d5a9337 100644--- a/products/signals/backend/test/test_auto_start.py+++ b/products/signals/backend/test/test_auto_start.py@@ -9,6 +9,7 @@ from social_django.models import UserSocialAuthfrom posthog.models import Organization, Team, Userfrom posthog.models.organization import OrganizationMembership+from posthog.models.scoping import team_scopefrom products.signals.backend.agent_runtime import AgentRuntimefrom products.signals.backend.auto_start import (@@ -23,11 +24,13 @@ from products.signals.backend.models import (SignalReport,SignalReportArtefact,SignalReportTask,+ SignalScoutRun,SignalSourceConfig,SignalUserAutonomyConfig,)from products.signals.backend.report_generation.research import Priorityfrom products.signals.backend.task_run_artefacts import TASK_RUN_TYPE_IMPLEMENTATION, signals_task_ids+from products.signals.backend.test.test_billing import _seed_canonical_scout_skillfrom products.tasks.backend.facade import api as tasks_facade@@ -256,6 +259,75 @@ def test_create_implementation_task_if_absent_is_idempotent(organization, team):assert signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION) == [str(created_tasks[0].id)]+ ("authoring_scout_skill", "declared_reason", "expected_reason"),+ [+ # System policy: reports authored by the health-check scout are frozen never-billable.+ ("signals-scout-health-checks", None, "posthog_health_check"),+ # Other scouts and pipeline reports stay billable.+ ("signals-scout-general", None, None),+ (None, None, None),+ # A caller that knows its PostHog-system origin can declare the exemption explicitly.+ (None, "posthog_onboarding", "posthog_onboarding"),+ ],+)+def test_create_implementation_task_freezes_billing_exemption(+ organization, team, authoring_scout_skill, declared_reason, expected_reason+):+ # The exemption must be stamped under the same lock that creates the implementation task —+ # before any billable PR run can exist — so no usage report can observe it flipping.+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ user = _create_org_member_with_github("[email protected]", organization, "OctoCat")+ report = SignalReport.objects.create(+ team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0+ )+ if authoring_scout_skill is not None:+ # Exemption policy requires the emitting skill row to still be the canonical seeded content.+ _seed_canonical_scout_skill(team, authoring_scout_skill)+ scout_task = Task.objects.create(team=team, title="scout", description="d")+ scout_task_run = TaskRun.objects.create(team=team, task=scout_task)+ with team_scope(team.id):+ SignalScoutRun.objects.create(+ team=team,+ task_run=scout_task_run,+ skill_name=authoring_scout_skill,+ skill_version=1,+ emitted_report_ids=[str(report.id)],+ )++ def _fake_create_and_run_task(**kwargs):+ task = Task.objects.create(+ team=team,+ title=kwargs["title"],+ description=kwargs["description"],+ created_by=user,+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )+ run = TaskRun.objects.create(task=task, team=team)+ 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),+ patch("products.signals.backend.auto_start.fetch_source_products_for_reports", return_value={}),+ ):+ created = _create_implementation_task_if_absent(+ team_id=team.id,+ report_id=str(report.id),+ title="t",+ description="d",+ user_id=user.id,+ repository="owner/repo",+ base_branch=None,+ billing_exempt_reason=declared_reason,+ )++ assert created is True+ report.refresh_from_db()+ assert report.billing_exempt_reason == expected_reason++@pytest.mark.django_dbdef test_create_implementation_task_threads_resolved_runtime(organization, team):Task = apps.get_model("tasks", "Task")diff --git a/products/signals/backend/test/test_billing.py b/products/signals/backend/test/test_billing.pyindex b5d02653454c..4d2dcc9ab68a 100644--- a/products/signals/backend/test/test_billing.py+++ b/products/signals/backend/test/test_billing.py@@ -10,8 +10,18 @@ from parameterized import parameterizedfrom posthog.models import Teamfrom products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION, TASK_RUN_TYPE_RESEARCH-from products.signals.backend.billing import SIGNALS_CREDITS_PER_REPORT_WITH_PR, get_signals_billing_credits_by_team-from products.signals.backend.models import SignalReport, SignalReportTask+from products.signals.backend.billing import (+ SIGNALS_CREDITS_PER_REPORT_WITH_PR,+ BillingExemptionError,+ FirstBillablePrRun,+ first_billable_pr_run,+ get_signals_billing_credits_by_team,+ mark_report_billing_exempt,+ system_billing_exempt_reason,+)+from products.signals.backend.models import SignalReport, SignalReportRefund, SignalReportTask, SignalScoutRun+from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hash+from products.skills.backend.models.skills import LLMSkillif TYPE_CHECKING:from products.tasks.backend.models import (@@ -41,9 +51,61 @@ def _task_run_model() -> type["TaskRunModel"]:return apps.get_model("tasks", "TaskRun")+def _seed_canonical_scout_skill(team: Team, skill_name: str) -> LLMSkill:+ """A team skill row that classifies as canonical: harness-seeded metadata whose stored+ canonical_hash matches the row's current content hash (like lazy seeding stamps it)."""+ skill = LLMSkill.objects.create(+ team=team,+ name=skill_name,+ description="d",+ body="canonical body",+ allowed_tools=[],+ metadata={"seeded_by": HARNESS_SEEDED_BY},+ version=1,+ is_latest=True,+ )+ skill.metadata["canonical_hash"] = _compute_row_hash(skill, [])+ skill.save(update_fields=["metadata"])+ return skill+++def _make_report(team: Team, *, status: str = SignalReport.Status.READY) -> SignalReport:+ return SignalReport.objects.create(team=team, status=status, signal_count=1, total_weight=1.0)+++def _make_pr_run(+ team: Team,+ report: SignalReport,+ *,+ created_at: datetime,+ pr_url: str | None = "https://github.com/x/y/pull/1",+ relationship: str = TASK_RUN_TYPE_IMPLEMENTATION,+ output: object = _UNSET,+) -> "TaskRunModel":+ Task, TaskRun = _task_model(), _task_run_model()+ task = Task.objects.create(+ team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT+ )+ SignalReportTask.objects.create(team=team, report=report, task=task, relationship=relationship)+ run_output = output if output is not _UNSET else ({"pr_url": pr_url} if pr_url is not None else {})+ return TaskRun.objects.create(team=team, task=task, output=run_output, created_at=created_at)+++def _make_refund(report: SignalReport, *, billing_path: str, pr_run_created_at: datetime | None = None) -> None:+ SignalReportRefund.objects.create(+ team=report.team,+ report=report,+ reason=SignalReportRefund.Reason.PR_INCORRECT,+ billing_path=billing_path,+ credits=SIGNALS_CREDITS_PER_REPORT_WITH_PR,+ pr_url="https://github.com/x/y/pull/1",+ pr_run_created_at=pr_run_created_at or _at(10),+ )++class TestSignalsBilling(BaseTest):def _report(self, *, team: Team | None = None, status: str = SignalReport.Status.READY) -> SignalReport:- return SignalReport.objects.create(team=team or self.team, status=status, signal_count=1, total_weight=1.0)+ return _make_report(team or self.team, status=status)def _pr_run(self,@@ -55,14 +117,9 @@ class TestSignalsBilling(BaseTest):relationship: str = TASK_RUN_TYPE_IMPLEMENTATION,output: object = _UNSET,) -> "TaskRunModel":- team = team or self.team- Task, TaskRun = _task_model(), _task_run_model()- task = Task.objects.create(- team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT+ return _make_pr_run(+ team or self.team, report, created_at=created_at, pr_url=pr_url, relationship=relationship, output=output)- SignalReportTask.objects.create(team=team, report=report, task=task, relationship=relationship)- run_output = output if output is not _UNSET else ({"pr_url": pr_url} if pr_url is not None else {})- return TaskRun.objects.create(team=team, task=task, output=run_output, created_at=created_at)def _credits(self) -> dict[int, int]:return dict(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END))@@ -259,6 +316,74 @@ class TestSignalsBilling(BaseTest):self._pr_run(report, created_at=_at(21))self.assertEqual(self._credits(), {self.team.id: 1500})+ def test_excluded_refund_removes_report_from_usage_deterministically(self) -> None:+ # The excluded path promises billing never learns the report existed — and every send+ # covering the day (scheduled, delayed-org re-send, manual re-run) must agree.+ report = self._report()+ self._pr_run(report, created_at=_at(10))+ _make_refund(report, billing_path=SignalReportRefund.BillingPath.EXCLUDED)+ self.assertEqual(self._credits(), {})+ self.assertEqual(self._credits(), {})++ def test_credited_refund_leaves_usage_truthful(self) -> None:+ # The credited path fixes the money via a billing-service credit; usage must stay intact.+ report = self._report()+ self._pr_run(report, created_at=_at(10))+ _make_refund(report, billing_path=SignalReportRefund.BillingPath.CREDITED)+ self.assertEqual(self._credits(), {self.team.id: 1500})++ def test_excluded_refund_only_affects_its_own_report(self) -> None:+ refunded = self._report()+ self._pr_run(refunded, created_at=_at(10))+ _make_refund(refunded, billing_path=SignalReportRefund.BillingPath.EXCLUDED)+ other = self._report()+ self._pr_run(other, created_at=_at(11))+ self.assertEqual(self._credits(), {self.team.id: 1500})++ @parameterized.expand(+ [+ ("excluded", SignalReportRefund.BillingPath.EXCLUDED),+ ("credited", SignalReportRefund.BillingPath.CREDITED),+ ]+ )+ def test_refunded_report_with_later_second_pr_never_bills(self, _name: str, billing_path: str) -> None:+ # Pins the emergent never-billed-again semantic: the refunded report's first PR run+ # predates any later period, so a second PR run is always caught by `billed_earlier` —+ # which is why the API blocks restoring refunded reports.+ report = self._report()+ self._pr_run(report, created_at=_at(10))+ _make_refund(report, billing_path=billing_path)+ self._pr_run(report, created_at=datetime(2026, 7, 15, tzinfo=UTC))+ july_credits = dict(get_signals_billing_credits_by_team(PERIOD_END, datetime(2026, 8, 1, tzinfo=UTC)))+ self.assertEqual(july_credits, {})++ def test_exempt_report_never_appears_in_any_usage_window(self) -> None:+ report = self._report()+ report.billing_exempt_reason = SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK+ report.save(update_fields=["billing_exempt_reason"])+ self._pr_run(report, created_at=_at(10))+ self._pr_run(report, created_at=datetime(2026, 7, 15, tzinfo=UTC))+ self.assertEqual(self._credits(), {})+ self.assertEqual(self._credits(), {})+ self.assertEqual(get_signals_billing_credits_by_team(PERIOD_END, datetime(2026, 8, 1, tzinfo=UTC)), [])++ def test_first_billable_pr_run_snapshots_earliest_billable_run(self) -> None:+ # The refund action snapshots this run's timestamp + URL and decides the billing path from+ # it — returning the latest (or a non-billable) run would replay the wrong charge.+ report = self._report()+ self._pr_run(report, created_at=_at(3), pr_url=None) # not billable, must not win+ self._pr_run(report, created_at=_at(5), pr_url="https://github.com/x/y/pull/1")+ self._pr_run(report, created_at=_at(12), pr_url="https://github.com/x/y/pull/2")+ self.assertEqual(+ first_billable_pr_run(report.id),+ FirstBillablePrRun(created_at=_at(5), pr_url="https://github.com/x/y/pull/1"),+ )++ def test_first_billable_pr_run_none_without_billable_run(self) -> None:+ report = self._report()+ self._pr_run(report, created_at=_at(3), pr_url=None)+ self.assertIsNone(first_billable_pr_run(report.id))+def test_aggregates_across_teams_and_reports(self) -> None:team_b = Team.objects.create(organization=self.organization, name="team-b")for _ in range(3):@@ -275,3 +400,68 @@ class TestSignalsBilling(BaseTest):def test_no_billable_reports_returns_empty(self) -> None:self.assertEqual(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END), [])+++class TestBillingExemptions(BaseTest):+ def test_mark_report_billing_exempt_sets_reason_before_billable_run(self) -> None:+ report = _make_report(self.team)+ changed = mark_report_billing_exempt(report, SignalReport.BillingExemptReason.POSTHOG_SYSTEM)+ report.refresh_from_db()+ self.assertTrue(changed)+ self.assertEqual(report.billing_exempt_reason, SignalReport.BillingExemptReason.POSTHOG_SYSTEM)++ def test_mark_report_billing_exempt_refuses_once_billable_run_exists(self) -> None:+ # The freeze rule: anything already billable is a refund, never a late exemption —+ # flipping the flag after a usage send may have observed the run breaks determinism.+ report = _make_report(self.team)+ _make_pr_run(self.team, report, created_at=_at(10))+ with self.assertRaises(BillingExemptionError):+ mark_report_billing_exempt(report, SignalReport.BillingExemptReason.POSTHOG_SYSTEM)+ report.refresh_from_db()+ self.assertIsNone(report.billing_exempt_reason)++ def test_mark_report_billing_exempt_never_rewrites_existing_reason(self) -> None:+ report = _make_report(self.team)+ mark_report_billing_exempt(report, SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK)+ changed = mark_report_billing_exempt(report, SignalReport.BillingExemptReason.POSTHOG_SYSTEM)+ report.refresh_from_db()+ self.assertFalse(changed)+ self.assertEqual(report.billing_exempt_reason, SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK)++ def _scout_run(self, skill_name: str, emitted_report_ids: list[str]) -> SignalScoutRun:+ Task, TaskRun = _task_model(), _task_run_model()+ task = Task.objects.create(team=self.team, title="scout", description="d")+ task_run = TaskRun.objects.create(team=self.team, task=task)+ return SignalScoutRun.objects.create(+ team=self.team,+ task_run=task_run,+ skill_name=skill_name,+ skill_version=1,+ emitted_report_ids=emitted_report_ids,+ )++ def test_system_policy_exempts_health_check_scout_reports_only(self) -> None:+ health_check_report = _make_report(self.team)+ other_scout_report = _make_report(self.team)+ pipeline_report = _make_report(self.team)+ self._scout_run("signals-scout-health-checks", [str(health_check_report.id)])+ self._scout_run("signals-scout-general", [str(other_scout_report.id)])++ # No skill row for the team: origin unprovable → fail closed, stays billable.+ self.assertIsNone(system_billing_exempt_reason(self.team.id, health_check_report.id))++ skill = _seed_canonical_scout_skill(self.team, "signals-scout-health-checks")+ self.assertEqual(+ system_billing_exempt_reason(self.team.id, health_check_report.id),+ SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK,+ )+ self.assertIsNone(system_billing_exempt_reason(self.team.id, other_scout_report.id))+ self.assertIsNone(system_billing_exempt_reason(self.team.id, pipeline_report.id))++ # A team-edited fork keeps the canonical name but is no longer PostHog's system:+ # the diverged row must stop minting exemptions.+ skill.body = "team-edited body"+ skill.save(update_fields=["body"])+ forked_report = _make_report(self.team)+ self._scout_run("signals-scout-health-checks", [str(forked_report.id)])+ self.assertIsNone(system_billing_exempt_reason(self.team.id, forked_report.id))diff --git a/products/signals/backend/test/test_refunds.py b/products/signals/backend/test/test_refunds.pynew file mode 100644index 000000000000..d74ff5307c70--- /dev/null+++ b/products/signals/backend/test/test_refunds.py@@ -0,0 +1,571 @@+import json+from datetime import UTC, datetime, timedelta+from decimal import Decimal++from freezegun import freeze_time+from posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import patch++from django.core.management import CommandError, call_command+from django.utils import timezone++from parameterized import parameterized+from rest_framework import status++# Load the API URLconf (and its pydantic.v1 import chain) before any freeze_time window:+# first-importing date-subclassing modules under freezegun's fake date raises a metaclass+# conflict, which standalone runs of this file otherwise hit on the first request.+import posthog.api.rest_router # noqa: F401+from posthog.models import Organization, Team++from products.signals.backend.billing import SIGNALS_CREDITS_PER_REPORT_WITH_PR+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportRefund+from products.signals.backend.tasks import (+ _OUT_OF_PERIOD_SYNC_ERROR,+ _REFUND_SYNC_MAX_RETRIES,+ sync_pending_signals_refund_credits,+ sync_signals_refund_credit,+)+from products.signals.backend.test.test_billing import _make_pr_run, _make_report++_PERIOD = ["2026-06-01T00:00:00Z", "2026-07-01T00:00:00Z"]+_NOW = "2026-06-15T12:00:00Z"+++def _make_refund(+ report: SignalReport,+ *,+ billing_path: str = SignalReportRefund.BillingPath.CREDITED,+ pr_run_created_at: datetime | None = None,+ # None models a row created before the frozen period bounds existed.+ period: tuple[datetime, datetime] | None = (+ datetime(2026, 6, 1, tzinfo=UTC),+ datetime(2026, 7, 1, tzinfo=UTC),+ ),+) -> SignalReportRefund:+ return SignalReportRefund.objects.create(+ team=report.team,+ report=report,+ reason=SignalReportRefund.Reason.PR_INCORRECT,+ billing_path=billing_path,+ credits=SIGNALS_CREDITS_PER_REPORT_WITH_PR,+ pr_url="https://github.com/x/y/pull/1",+ pr_run_created_at=pr_run_created_at or datetime(2026, 6, 10, tzinfo=UTC),+ period_start=period[0] if period else None,+ period_end=period[1] if period else None,+ )+++@patch("posthoganalytics.feature_enabled", return_value=True)+class TestSignalReportRefundAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.organization.usage = {"period": _PERIOD}+ self.organization.save()++ def _refund_url(self, report_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/refund/"++ def _state_url(self, report_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/state/"++ def _report_with_pr(+ self, *, pr_created_at: datetime, report_status: str = SignalReport.Status.READY+ ) -> SignalReport:+ report = _make_report(self.team, status=report_status)+ _make_pr_run(self.team, report, created_at=pr_created_at)+ return report++ def _refund(self, report: SignalReport, body: dict | None = None):+ return self.client.post(self._refund_url(str(report.id)), body or {"reason": "pr_not_useful"}, format="json")++ @freeze_time(_NOW)+ def test_refund_earlier_in_period_goes_credited_and_archives(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, 9, 30, tzinfo=UTC))+ response = self._refund(report, {"reason": "pr_incorrect", "note": "does not fix the bug"})++ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert body["billing_path"] == "credited"+ assert body["credits"] == 1500+ assert body["reason"] == "pr_incorrect"+ assert body["pr_url"] == "https://github.com/x/y/pull/1"+ assert body["already_refunded"] is False+ assert body["billing_synced"] is False+ assert body["credit_amount_usd"] is None++ report.refresh_from_db()+ assert report.status == SignalReport.Status.SUPPRESSED+ refund = report.refund+ assert refund.billing_path == SignalReportRefund.BillingPath.CREDITED+ assert refund.pr_run_created_at == datetime(2026, 6, 10, 9, 30, tzinfo=UTC)+ # The accepted billing period is frozen on the row — the sync payload reports these+ # bounds, so a sync landing after rollover still credits the right period.+ assert refund.period_start == datetime(2026, 6, 1, tzinfo=UTC)+ assert refund.period_end == datetime(2026, 7, 1, tzinfo=UTC)+ assert refund.created_by_id == self.user.id+ assert refund.note == "does not fix the bug"++ dismissal = SignalReportArtefact.objects.get(report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL)+ content = json.loads(dismissal.content)+ assert content["reason"] == "refunded"+ assert content["note"] == "does not fix the bug"++ @freeze_time(_NOW)+ def test_refund_on_pr_run_day_goes_excluded(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 15, 8, 0, tzinfo=UTC))+ response = self._refund(report)+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["billing_path"] == "excluded"++ @freeze_time("2026-06-15T00:30:00Z")+ def test_refund_just_after_utc_midnight_goes_credited(self, _flag):+ # The path rule is the PR run's UTC day, not "before the 03:45 send" — a 23:50 PR refunded+ # at 00:30 must go credited even though the usage report hasn't shipped yet.+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 14, 23, 50, tzinfo=UTC))+ response = self._refund(report)+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["billing_path"] == "credited"++ @freeze_time(_NOW)+ def test_refund_without_billable_pr_is_rejected(self, _flag):+ report = _make_report(self.team)+ response = self._refund(report)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "no billable implementation PR" in response.json()["error"]++ @freeze_time(_NOW)+ def test_refund_for_previous_period_pr_is_rejected(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 5, 20, tzinfo=UTC))+ response = self._refund(report)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "previous billing period" in response.json()["error"]++ @parameterized.expand(+ [+ ("pr_in_current_month", datetime(2026, 6, 10, tzinfo=UTC), status.HTTP_200_OK),+ ("pr_in_previous_month", datetime(2026, 5, 20, tzinfo=UTC), status.HTTP_400_BAD_REQUEST),+ ]+ )+ @freeze_time(_NOW)+ def test_missing_billing_period_falls_back_to_calendar_month(self, _flag, _name, pr_created_at, expected_status):+ self.organization.usage = None+ self.organization.save()+ report = self._report_with_pr(pr_created_at=pr_created_at)+ response = self._refund(report)+ assert response.status_code == expected_status++ @parameterized.expand(+ [+ ("eligible", None),+ ("out_of_period", "out_of_period"),+ ("no_billable_pr", "no_billable_pr"),+ ("already_refunded", "already_refunded"),+ ("billing_exempt", "billing_exempt"),+ ]+ )+ @freeze_time(_NOW)+ def test_report_response_carries_refund_ineligibility_reason(self, _flag, case, expected):+ # The serializer field shares the refund endpoint's eligibility decision (annotation ++ # period context + helper); a wiring regression would re-enable buttons that only 400.+ if case == "no_billable_pr":+ report = _make_report(self.team)+ else:+ pr_at = datetime(2026, 5, 20, tzinfo=UTC) if case == "out_of_period" else datetime(2026, 6, 10, tzinfo=UTC)+ report = self._report_with_pr(pr_created_at=pr_at)+ if case == "already_refunded":+ _make_refund(report)+ if case == "billing_exempt":+ SignalReport.objects.filter(id=report.id).update(+ billing_exempt_reason=SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK+ )++ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/")++ assert response.status_code == 200+ assert response.json()["refund_ineligibility_reason"] == expected++ @freeze_time(_NOW)+ def test_refund_on_exempt_report_is_rejected(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ SignalReport.objects.filter(id=report.id).update(+ billing_exempt_reason=SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK+ )+ response = self._refund(report)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "never-billable" in response.json()["error"]++ @freeze_time(_NOW)+ def test_second_refund_is_idempotent(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ first = self._refund(report, {"reason": "pr_incorrect"})+ second = self._refund(report, {"reason": "duplicate"})++ assert first.status_code == status.HTTP_200_OK+ assert second.status_code == status.HTTP_200_OK+ assert second.json()["already_refunded"] is True+ # The original refund is returned unchanged — the second reason never sticks.+ assert second.json()["reason"] == "pr_incorrect"+ assert second.json()["id"] == first.json()["id"]+ assert SignalReportRefund.objects.filter(report=report).count() == 1++ @freeze_time(_NOW)+ def test_refund_reaches_already_archived_report(self, _flag):+ # An archived-but-charged report must still be refundable (suppressed reports are hidden+ # from most by-id actions); it stays suppressed.+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ report.transition_to(SignalReport.Status.SUPPRESSED)+ report.save()+ response = self._refund(report)+ assert response.status_code == status.HTTP_200_OK+ report.refresh_from_db()+ assert report.status == SignalReport.Status.SUPPRESSED++ @freeze_time(_NOW)+ def test_refund_keeps_resolved_report_resolved(self, _flag):+ report = self._report_with_pr(+ pr_created_at=datetime(2026, 6, 10, tzinfo=UTC), report_status=SignalReport.Status.RESOLVED+ )+ response = self._refund(report)+ assert response.status_code == status.HTTP_200_OK+ report.refresh_from_db()+ assert report.status == SignalReport.Status.RESOLVED+ # The permanent marker still lands even though the status did not change.+ assert SignalReportArtefact.objects.filter(+ report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL+ ).exists()++ @freeze_time(_NOW)+ def test_invalid_reason_is_rejected(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ response = self._refund(report, {"reason": "because"})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not SignalReportRefund.objects.filter(report=report).exists()++ @freeze_time(_NOW)+ def test_credited_refund_enqueues_billing_sync_on_commit(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ with patch("products.signals.backend.views.sync_signals_refund_credit.delay") as mock_delay:+ with self.captureOnCommitCallbacks(execute=True):+ response = self._refund(report)+ assert response.status_code == status.HTTP_200_OK+ mock_delay.assert_called_once_with(str(report.refund.id))++ @freeze_time(_NOW)+ def test_excluded_refund_never_calls_billing(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 15, 8, 0, tzinfo=UTC))+ with patch("products.signals.backend.views.sync_signals_refund_credit.delay") as mock_delay:+ with self.captureOnCommitCallbacks(execute=True):+ response = self._refund(report)+ assert response.status_code == status.HTTP_200_OK+ mock_delay.assert_not_called()++ @freeze_time(_NOW)+ def test_refund_fires_analytics_event(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ with patch("products.signals.backend.views.report_user_action") as mock_report:+ self._refund(report)+ mock_report.assert_called_once()+ assert mock_report.call_args.args[1] == "signals_pr_refund_created"+ properties = mock_report.call_args.kwargs["properties"]+ assert properties["billing_path"] == "credited"+ assert properties["credits"] == 1500+ assert properties["pr_merged"] is False+ assert properties["days_since_pr"] == 5++ @freeze_time(_NOW)+ def test_restore_of_refunded_report_is_blocked(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ assert self._refund(report).status_code == status.HTTP_200_OK++ response = self.client.post(self._state_url(str(report.id)), {"state": "potential"}, format="json")+ assert response.status_code == status.HTTP_409_CONFLICT+ assert response.json()["error"] == "Refunded reports can't be restored."+ report.refresh_from_db()+ assert report.status == SignalReport.Status.SUPPRESSED++ @freeze_time(_NOW)+ def test_bulk_restore_of_refunded_report_is_blocked(self, _flag):+ refunded = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ assert self._refund(refunded).status_code == status.HTTP_200_OK+ archived = _make_report(self.team)+ archived.transition_to(SignalReport.Status.SUPPRESSED)+ archived.save()++ response = self.client.post(+ f"/api/projects/{self.team.id}/signals/reports/bulk-state/",+ {"ids": [str(refunded.id), str(archived.id)], "state": "potential"},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ results = {r["id"]: r for r in response.json()["results"]}+ assert results[str(refunded.id)]["outcome"] == "skipped"+ assert results[str(refunded.id)]["detail"] == "Refunded reports can't be restored."+ assert results[str(archived.id)]["outcome"] == "transitioned"+ refunded.refresh_from_db()+ assert refunded.status == SignalReport.Status.SUPPRESSED++ @freeze_time(_NOW)+ def test_report_response_includes_refund_and_exemption_fields(self, _flag):+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ self._refund(report)+ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/")+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["refund"]["billing_path"] == "credited"+ assert body["refund"]["reason"] == "pr_not_useful"+ assert body["billing_exempt_reason"] is None++ @freeze_time(_NOW)+ def test_refund_summary_aggregates_credited_refunds_org_wide(self, _flag):+ # Two teams in the org contribute; excluded-path, out-of-period, and foreign-org refunds don't.+ report_a = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ _make_refund(report_a, pr_run_created_at=datetime(2026, 6, 10, tzinfo=UTC))+ sibling_team = Team.objects.create(organization=self.organization, name="sibling")+ report_b = _make_report(sibling_team)+ _make_refund(report_b, pr_run_created_at=datetime(2026, 6, 12, tzinfo=UTC))+ excluded = _make_report(self.team)+ _make_refund(+ excluded,+ billing_path=SignalReportRefund.BillingPath.EXCLUDED,+ pr_run_created_at=datetime(2026, 6, 13, tzinfo=UTC),+ )+ out_of_period = _make_report(self.team)+ _make_refund(out_of_period, pr_run_created_at=datetime(2026, 5, 20, tzinfo=UTC))+ other_org = Organization.objects.create(name="other")+ other_team = Team.objects.create(organization=other_org, name="other")+ foreign = _make_report(other_team)+ _make_pr_run(other_team, foreign, created_at=datetime(2026, 6, 14, tzinfo=UTC))+ _make_refund(foreign, pr_run_created_at=datetime(2026, 6, 14, tzinfo=UTC))++ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/refund-summary/")+ assert response.status_code == status.HTTP_200_OK+ # period_billable_credits: only report_a has a billable PR run in this org (credited+ # refunds stay counted — usage is truthful); the foreign org's billable PR must not leak in.+ assert response.json() == {+ "credited_refund_count": 2,+ "credited_credits": 3000,+ "period_billable_credits": 1500,+ }++ @freeze_time(_NOW)+ def test_refund_summary_counts_unreported_prs_live_until_excluded_refund(self, _flag):+ # A PR created today hasn't shipped to billing yet but must count in the live number,+ # and a same-day (excluded-path) refund must visibly un-count it.+ report = self._report_with_pr(pr_created_at=datetime(2026, 6, 15, 8, 0, tzinfo=UTC))+ url = f"/api/projects/{self.team.id}/signals/reports/refund-summary/"++ assert self.client.get(url).json()["period_billable_credits"] == 1500+ assert self._refund(report).json()["billing_path"] == "excluded"+ assert self.client.get(url).json()["period_billable_credits"] == 0+++class TestSignalReportRefundFlagGate(APIBaseTest):+ @parameterized.expand([("refund",), ("refund_summary",)])+ @patch("posthoganalytics.feature_enabled", return_value=False)+ def test_endpoints_unavailable_with_flag_off(self, action_path, _flag):+ report = _make_report(self.team)+ if action_path == "refund":+ url = f"/api/projects/{self.team.id}/signals/reports/{report.id}/refund/"+ response = self.client.post(url, {"reason": "other"}, format="json")+ else:+ url = f"/api/projects/{self.team.id}/signals/reports/refund-summary/"+ response = self.client.get(url)+ assert response.status_code == status.HTTP_404_NOT_FOUND+ assert not SignalReportRefund.objects.filter(report=report).exists()+++class TestSyncSignalsRefundCredit(BaseTest):+ def _credited_refund(self) -> SignalReportRefund:+ report = _make_report(self.team)+ return _make_refund(report)++ def test_success_records_credit_and_contract_payload(self):+ # The org's billing period has rolled over since the refund was accepted: the payload+ # must report the bounds frozen on the refund row, not the current period — recomputing+ # at sync time is the drift that loses post-rollover credits.+ self.organization.usage = {"period": ["2026-07-01T00:00:00Z", "2026-08-01T00:00:00Z"]}+ self.organization.save()+ refund = self._credited_refund()+ with patch(+ "ee.billing.billing_manager.BillingManager.dispute_signals_pr",+ return_value={"credit_amount_usd": "15.00", "credit_id": "c1", "already_processed": False},+ ) as mock_dispute:+ sync_signals_refund_credit(str(refund.id))++ refund.refresh_from_db()+ assert refund.credit_amount_usd == Decimal("15.00")+ assert refund.billing_synced_at is not None+ assert refund.billing_sync_error is None++ organization, payload = mock_dispute.call_args.args+ assert organization.id == self.organization.id+ # The frozen cross-repo contract shape — billing keys idempotency on refund_id and+ # credits against the accepted period carried in metadata.period_start/period_end.+ assert payload == {+ "refund_id": str(refund.id),+ "credits": 1500,+ "metadata": {+ "team_id": self.team.id,+ "report_id": str(refund.report_id),+ "pr_url": "https://github.com/x/y/pull/1",+ "pr_run_created_at": "2026-06-10T00:00:00+00:00",+ "period_start": "2026-06-01T00:00:00+00:00",+ "period_end": "2026-07-01T00:00:00+00:00",+ },+ }++ def test_payload_falls_back_to_current_period_for_rows_without_frozen_bounds(self):+ # Rows created before the frozen bounds existed must still sync (with sync-time bounds)+ # rather than crash on the null fields.+ self.organization.usage = {"period": _PERIOD}+ self.organization.save()+ refund = _make_refund(_make_report(self.team), period=None)+ with patch(+ "ee.billing.billing_manager.BillingManager.dispute_signals_pr",+ return_value={"credit_amount_usd": "15.00", "credit_id": "c1", "already_processed": False},+ ) as mock_dispute:+ sync_signals_refund_credit(str(refund.id))+ metadata = mock_dispute.call_args.args[1]["metadata"]+ assert metadata["period_start"] == "2026-06-01T00:00:00+00:00"+ assert metadata["period_end"] == "2026-07-01T00:00:00+00:00"++ def test_zero_credit_outcome_still_marks_synced(self):+ # "0.00" is a legitimate business outcome (free tier / free plan) — the row must complete.+ refund = self._credited_refund()+ with patch(+ "ee.billing.billing_manager.BillingManager.dispute_signals_pr",+ return_value={+ "credit_amount_usd": "0.00",+ "credit_id": None,+ "already_processed": False,+ "zero_reason": "no_marginal_cost",+ },+ ):+ sync_signals_refund_credit(str(refund.id))+ refund.refresh_from_db()+ assert refund.credit_amount_usd == Decimal("0.00")+ assert refund.billing_synced_at is not None++ def test_out_of_period_zero_records_error_instead_of_synced(self):+ # A $0 with zero_reason=out_of_period means billing could no longer credit the frozen+ # refund period — the row must surface as a sync error for manual recovery, not close+ # as a synced $0.+ refund = self._credited_refund()+ with patch(+ "ee.billing.billing_manager.BillingManager.dispute_signals_pr",+ return_value={+ "credit_amount_usd": "0.00",+ "credit_id": None,+ "already_processed": False,+ "zero_reason": "out_of_period",+ },+ ):+ with patch("products.signals.backend.tasks.ph_scoped_capture") as mock_capture_cm:+ mock_capture = mock_capture_cm.return_value.__enter__.return_value+ sync_signals_refund_credit(str(refund.id))+ refund.refresh_from_db()+ assert refund.billing_synced_at is None+ assert refund.credit_amount_usd is None+ assert refund.billing_sync_error == _OUT_OF_PERIOD_SYNC_ERROR+ assert mock_capture.call_args.kwargs["event"] == "signals_pr_refund_credit_failed"++ def test_already_synced_refund_is_not_resent(self):+ refund = self._credited_refund()+ refund.billing_synced_at = timezone.now()+ refund.save(update_fields=["billing_synced_at"])+ with patch("ee.billing.billing_manager.BillingManager.dispute_signals_pr") as mock_dispute:+ sync_signals_refund_credit(str(refund.id))+ mock_dispute.assert_not_called()++ def test_delivery_losing_the_sync_race_does_not_rerecord_or_emit(self):+ # The on-commit enqueue and the hourly sweeper can both deliver the same refund; if a+ # concurrent delivery commits the sync while this one's billing call is in flight, this+ # one must not overwrite the row or emit a second issued event.+ refund = self._credited_refund()+ concurrent_synced_at = timezone.now()++ def _concurrent_delivery_wins(*args, **kwargs):+ SignalReportRefund.objects.filter(id=refund.id).update(+ credit_amount_usd=Decimal("15.00"), billing_synced_at=concurrent_synced_at+ )+ return {"credit_amount_usd": "15.00", "credit_id": "c1", "already_processed": True}++ with patch(+ "ee.billing.billing_manager.BillingManager.dispute_signals_pr", side_effect=_concurrent_delivery_wins+ ):+ with patch("products.signals.backend.tasks.ph_scoped_capture") as mock_capture_cm:+ sync_signals_refund_credit(str(refund.id))++ refund.refresh_from_db()+ assert refund.billing_synced_at == concurrent_synced_at+ mock_capture_cm.assert_not_called()++ def test_excluded_refund_never_calls_billing(self):+ report = _make_report(self.team)+ refund = _make_refund(report, billing_path=SignalReportRefund.BillingPath.EXCLUDED)+ with patch("ee.billing.billing_manager.BillingManager.dispute_signals_pr") as mock_dispute:+ sync_signals_refund_credit(str(refund.id))+ mock_dispute.assert_not_called()++ def test_failure_before_retry_exhaustion_does_not_record_terminal_error(self):+ refund = self._credited_refund()+ with patch(+ "ee.billing.billing_manager.BillingManager.dispute_signals_pr", side_effect=ValueError("billing down")+ ):+ with self.assertRaises(Exception):+ sync_signals_refund_credit(str(refund.id))+ refund.refresh_from_db()+ assert refund.billing_synced_at is None+ assert refund.billing_sync_error is None++ def test_exhausted_retries_record_terminal_error_and_event(self):+ refund = self._credited_refund()+ task = sync_signals_refund_credit+ with patch(+ "ee.billing.billing_manager.BillingManager.dispute_signals_pr", side_effect=ValueError("billing down")+ ):+ with patch("products.signals.backend.tasks.ph_scoped_capture") as mock_capture_cm:+ mock_capture = mock_capture_cm.return_value.__enter__.return_value+ task.push_request(retries=_REFUND_SYNC_MAX_RETRIES)+ try:+ task.run(str(refund.id))+ finally:+ task.pop_request()+ refund.refresh_from_db()+ assert refund.billing_synced_at is None+ assert "billing down" in (refund.billing_sync_error or "")+ assert mock_capture.call_args.kwargs["event"] == "signals_pr_refund_credit_failed"++ def test_sweeper_reenqueues_only_stale_unsynced_credited_rows(self):+ pending = self._credited_refund()+ synced = self._credited_refund()+ synced.billing_synced_at = timezone.now()+ synced.save(update_fields=["billing_synced_at"])+ _make_refund(_make_report(self.team), billing_path=SignalReportRefund.BillingPath.EXCLUDED)+ ancient = self._credited_refund()+ SignalReportRefund.objects.filter(id=ancient.id).update(created_at=timezone.now() - timedelta(days=8))+ rollover_lost = self._credited_refund()+ SignalReportRefund.objects.filter(id=rollover_lost.id).update(billing_sync_error=_OUT_OF_PERIOD_SYNC_ERROR)++ with patch("products.signals.backend.tasks.sync_signals_refund_credit.delay") as mock_delay:+ sync_pending_signals_refund_credits()++ mock_delay.assert_called_once_with(str(pending.id))+++class TestExemptSignalReportBillingCommand(BaseTest):+ def test_marks_report_exempt(self):+ report = _make_report(self.team)+ call_command("exempt_signal_report_billing", str(self.team.id), str(report.id), "posthog_system")+ report.refresh_from_db()+ assert report.billing_exempt_reason == SignalReport.BillingExemptReason.POSTHOG_SYSTEM++ def test_refuses_once_billable_pr_run_exists(self):+ report = _make_report(self.team)+ _make_pr_run(self.team, report, created_at=datetime(2026, 6, 10, tzinfo=UTC))+ with self.assertRaises(CommandError) as ctx:+ call_command("exempt_signal_report_billing", str(self.team.id), str(report.id), "posthog_system")+ assert "use a refund" in str(ctx.exception)+ report.refresh_from_db()+ assert report.billing_exempt_reason is Nonediff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.pyindex fef97e152b80..346ab9ef2600 100644--- a/products/signals/backend/test/test_signal_queries.py+++ b/products/signals/backend/test/test_signal_queries.py@@ -9,12 +9,12 @@ from parameterized import parameterizedfrom posthog.clickhouse.client import sync_execute-from products.signals.backend.temporal.signal_queries import (+from products.signals.backend.signal_metadata import (EMBEDDING_MODEL,ReportSignalMeta,- fetch_signals_for_report_sync,fetch_source_products_for_reports,)+from products.signals.backend.temporal.signal_queries import fetch_signals_for_report_sync_MODEL_TABLE = f"distributed_posthog_document_embeddings_{EMBEDDING_MODEL.value.replace('-', '_')}"_EMBEDDING = [0.0] * 1536diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex ab22ded385f2..3a01c2ded90c 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -22,8 +22,8 @@ from posthog.models.team.team import Teamfrom products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reportsfrom products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask+from products.signals.backend.signal_metadata import ReportSignalMetafrom products.signals.backend.task_run_artefacts import append_task_run_artefact, record_implementation_task-from products.signals.backend.temporal.signal_queries import ReportSignalMetaif TYPE_CHECKING:from products.tasks.backend.models import Task, TaskRundiff --git a/products/signals/backend/test/test_task_run_artefacts.py b/products/signals/backend/test/test_task_run_artefacts.pyindex 4f505a298474..4c3d20685664 100644--- a/products/signals/backend/test/test_task_run_artefacts.py+++ b/products/signals/backend/test/test_task_run_artefacts.py@@ -161,6 +161,20 @@ class TestTaskRunArtefacts(BaseTest):record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))assert SignalReportTask.objects.filter(report=report, task=task).count() == 1+ def test_record_implementation_task_declared_billing_exemption_marks_report(self):+ # A caller that knows its origin is PostHog-system freezes the exemption in the same+ # transaction that records the task — dropping this plumbing would silently bill it.+ report = self._report()+ task = self._task()+ record_implementation_task(+ team_id=self.team.id,+ report_id=str(report.id),+ task_id=str(task.id),+ billing_exempt_reason=SignalReport.BillingExemptReason.POSTHOG_ONBOARDING,+ )+ report.refresh_from_db()+ assert report.billing_exempt_reason == SignalReport.BillingExemptReason.POSTHOG_ONBOARDING+def _final_report(self) -> CustomAgentFinalReport:return CustomAgentFinalReport(title="title",diff --git a/products/signals/backend/utils.py b/products/signals/backend/utils.pyindex 5a52824d9c16..9bd1b86bc413 100644--- a/products/signals/backend/utils.py+++ b/products/signals/backend/utils.py@@ -1,9 +1,6 @@# Re-export from the canonical location for backward compatibility-from products.signals.backend.temporal.signal_queries import (- EMBEDDING_MODEL,- _ensure_tz_aware,- soft_delete_report_signals,-)+from products.signals.backend.signal_metadata import EMBEDDING_MODEL+from products.signals.backend.temporal.signal_queries import _ensure_tz_aware, soft_delete_report_signals__all__ = ["EMBEDDING_MODEL",diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex e83086bd877a..1cc9be038505 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -1,6 +1,6 @@import jsonimport uuid-from datetime import timedelta+from datetime import UTC, timedeltafrom typing import castfrom django.conf import settings@@ -20,12 +20,15 @@ from django.db.models import (Prefetch,Q,Subquery,+ Sum,Value,When,)from django.db.models.functions import Cast, Coalesce+from django.utils import timezoneimport structlog+import posthoganalyticsfrom asgiref.sync import async_to_syncfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view@@ -46,6 +49,7 @@ from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import InternalAPIAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthenticationfrom posthog.egress.github.transport import GitHubRateLimitError+from posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity@@ -66,6 +70,17 @@ from products.signals.backend.artefact_schemas import (TitleChange,parse_artefact_content,)+from products.signals.backend.billing import (+ REFUND_INELIGIBLE_BILLING_EXEMPT,+ REFUND_INELIGIBLE_NO_BILLABLE_PR,+ REFUND_INELIGIBLE_OUT_OF_PERIOD,+ SIGNALS_CREDITS_PER_REPORT_WITH_PR,+ annotate_first_billable_pr_run_at,+ current_billing_period_bounds,+ first_billable_pr_run,+ period_billable_credits_for_org,+ refund_ineligibility_reason,+)from products.signals.backend.facade.api import emit_signalfrom products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reportsfrom products.signals.backend.models import (@@ -74,6 +89,7 @@ from products.signals.backend.models import (InvalidStatusTransition,SignalReport,SignalReportArtefact,+ SignalReportRefund,SignalSourceConfig,SignalTeamConfig,SignalUserAutonomyConfig,@@ -93,17 +109,20 @@ from products.signals.backend.serializers import (SignalReportArtefactSerializer,SignalReportArtefactWriteResponseSerializer,SignalReportArtefactWriteSerializer,+ SignalReportRefundSerializer,SignalReportSerializer,SignalSourceConfigSerializer,SignalTeamConfigSerializer,SignalUserAutonomyConfigCreateSerializer,SignalUserAutonomyConfigSerializer,)+from products.signals.backend.signal_metadata import fetch_source_products_for_reportsfrom products.signals.backend.task_attribution import (TASK_ID_HEADER,resolve_request_attribution,resolve_task_id_from_header,)+from products.signals.backend.tasks import sync_signals_refund_creditfrom products.signals.backend.temporal.backfill_error_tracking import (BackfillErrorTrackingInput,BackfillErrorTrackingWorkflow,@@ -114,7 +133,6 @@ from products.signals.backend.temporal.reingestion import SignalReportReingestiofrom products.signals.backend.temporal.signal_queries import (fetch_report_ids_for_source_products,fetch_signals_for_report_sync,- fetch_source_products_for_reports,)from products.signals.backend.temporal.types import (SignalReportDeletionWorkflowInputs,@@ -528,6 +546,80 @@ class SignalReportBulkStateResponseSerializer(serializers.Serializer):not_found_count = serializers.IntegerField(help_text="Number of requested ids not visible to the caller.")+# Whole PR-refund feature gate. Checked server-side (not just in the UI) and keyed on the+# organization, matching the refund window (the org's billing period).+SIGNALS_PR_REFUNDS_FEATURE_FLAG = "signals-pr-refunds"+++# User-facing message for each shared `refund_ineligibility_reason` the refund action rejects on+# (`already_refunded` never reaches a 400 — it takes the idempotent 200 path instead).+_REFUND_INELIGIBLE_MESSAGES = {+ REFUND_INELIGIBLE_BILLING_EXEMPT: "This report is marked never-billable, so there is nothing to refund.",+ REFUND_INELIGIBLE_NO_BILLABLE_PR: "This report has no billable implementation PR to refund.",+ REFUND_INELIGIBLE_OUT_OF_PERIOD: "This PR was billed in a previous billing period and can no longer be refunded.",+}+++class SignalReportRefundRequestSerializer(serializers.Serializer):+ reason = serializers.ChoiceField(+ choices=SignalReportRefund.Reason.choices,+ help_text=(+ "Why this PR is being refunded. One of: pr_incorrect (the PR doesn't address what the "+ "report promised), pr_not_useful (technically fine but not worth paying for), duplicate "+ "(covers work already charged elsewhere), other. Required — refund reviews key on it."+ ),+ )+ note = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=SIGNAL_REPORT_DISMISSAL_NOTE_MAX_LENGTH,+ help_text=(+ "Optional free-form context for the refund; stored on the refund and echoed in the "+ "report's dismissal artefact. Capped at 4000 characters."+ ),+ )+++class SignalReportRefundResponseSerializer(SignalReportRefundSerializer):+ already_refunded = serializers.BooleanField(+ read_only=True,+ default=False,+ help_text=(+ "True when the report already had a refund and that existing refund is returned "+ "unchanged — refunds are one-per-report and repeat calls are idempotent."+ ),+ )++ class Meta(SignalReportRefundSerializer.Meta):+ fields = [*SignalReportRefundSerializer.Meta.fields, "already_refunded"]+ read_only_fields = fields+++class SignalReportRefundSummaryResponseSerializer(serializers.Serializer):+ credited_refund_count = serializers.IntegerField(+ help_text=(+ "Number of credited-path refunds across the whole organization whose refunded PR run "+ "falls in the current billing period. Excluded-path refunds never reach billing usage, "+ "so they are deliberately absent."+ ),+ )+ credited_credits = serializers.IntegerField(+ help_text=(+ "Total signals credits those refunds returned (1 credit = $0.01). Divide by the flat "+ "per-PR charge to get the number of PRs to subtract from billing usage."+ ),+ )+ period_billable_credits = serializers.IntegerField(+ help_text=(+ "The organization's live billable signals credits for the current billing period, "+ "computed by the same rules as the nightly usage report — including PRs created today "+ "that billing hasn't recorded yet, and already excluding refund-excluded and "+ "billing-exempt reports. Take the max of this and billing's recorded usage for a live "+ "PR count that reacts to new PRs and same-day refunds immediately."+ ),+ )++class SignalReportContentUpdateSerializer(serializers.Serializer):"""Editable human-facing fields on a signal report (PATCH).@@ -612,6 +704,8 @@ class SignalReportViewSet(qs = self._apply_signal_report_priority_filter(qs)qs = self._prefetch_signal_report_priority_artefacts(qs)qs = self._annotate_is_suggested_reviewer(qs)+ # Batched billable-moment lookup for the serializer's refund_ineligibility_reason field.+ qs = annotate_first_billable_pr_run_at(qs)if self.action != "list":qs = self._annotate_implementation_pr_url(qs)return qs@@ -626,8 +720,13 @@ class SignalReportViewSet(.values("count"),output_field=IntegerField(),)- return queryset.filter(team=self.team).annotate(- artefact_count=Coalesce(artefact_count_subquery, Value(0), output_field=IntegerField()),+ # select_related("refund"): the serializer renders the reverse OneToOne inline.+ return (+ queryset.filter(team=self.team)+ .select_related("refund")+ .annotate(+ artefact_count=Coalesce(artefact_count_subquery, Value(0), output_field=IntegerField()),+ ))def _exclude_deleted_signal_reports(self, queryset):@@ -642,10 +741,11 @@ class SignalReportViewSet(# `status` filter. These are the read/reopen paths the inbox's Dismissed tab needs:# `state` reopens a dismissed report, `retrieve` loads its detail, and `signals`# loads its evidence. `bulk_state` is included so a bulk restore (state='potential')- # can reach suppressed reports too. Mutating-by-ID actions (delete, reingest) are+ # can reach suppressed reports too. `refund` is included so an already-archived but+ # billed report can still be refunded. Mutating-by-ID actions (delete, reingest) are# deliberately NOT here, so a suppressed report stays unreachable for those and keeps# returning 404 — matching the existing contract.- _SUPPRESSED_VISIBLE_ACTIONS = frozenset({"state", "bulk_state", "retrieve", "signals"})+ _SUPPRESSED_VISIBLE_ACTIONS = frozenset({"state", "bulk_state", "retrieve", "signals", "refund"})# Human-readable explanation per bulk outcome, surfaced in each result's `detail` field# (transitioned needs none — its `status` already says where the report landed).@@ -1011,7 +1111,13 @@ class SignalReportViewSet(return login.lower() if login else Nonedef get_serializer_context(self):- return {**super().get_serializer_context(), "team": self.team}+ return {+ **super().get_serializer_context(),+ "team": self.team,+ # For the serializer's refund_ineligibility_reason field — computed once per request,+ # not per report (the bounds are org-level).+ "billing_period_bounds": current_billing_period_bounds(self.organization),+ }def _enriched_report_context(self, report: SignalReport) -> dict:# Detail-view parity with list(): inject the source-product and PR-url maps the@@ -1355,7 +1461,7 @@ class SignalReportViewSet(serializer.is_valid(raise_exception=True)data = serializer.validated_data- outcome = self._transition_report_state(+ outcome, detail = self._transition_report_state(report,target=data["state"],dismissal_reason=data.get("dismissal_reason"),@@ -1365,12 +1471,12 @@ class SignalReportViewSet(if outcome == SignalReportBulkStateOutcome.SKIPPED:return Response(- {"error": "Invalid state transition for this report."},+ {"error": detail or "Invalid state transition for this report."},status=status.HTTP_409_CONFLICT,)if outcome == SignalReportBulkStateOutcome.FAILED:return Response(- {"error": "Invalid data for state transition."},+ {"error": detail or "Invalid data for state transition."},status=status.HTTP_400_BAD_REQUEST,)@@ -1384,13 +1490,15 @@ class SignalReportViewSet(dismissal_reason: str | None,dismissal_note: str | None,snooze_for: int | None,- ) -> "SignalReportBulkStateOutcome":+ ) -> "tuple[SignalReportBulkStateOutcome, str | None]":"""Apply one report state transition (plus optional dismissal artefact) and return a- compact outcome. Shared by the single `state` action and the bulk `bulk_state` action- so both honour the same restore/snooze semantics and transition guards. Expected- invalid transitions are returned as outcomes (never raised) so a bulk run can record a- per-id result and keep going.+ compact `(outcome, detail)` pair — `detail` is a caller-facing explanation for+ non-transitioned outcomes when the generic per-outcome message isn't enough. Shared by+ the single `state` action and the bulk `bulk_state` action so both honour the same+ restore/snooze semantics and transition guards. Expected invalid transitions are+ returned as outcomes (never raised) so a bulk run can record a per-id result and keep+ going.Only `snooze_for` (on a snooze back to "potential") is caller-controllable. Every other`transition_to` kwarg (signals_at_run_increment, reset_weight, title, summary, error) is an@@ -1402,6 +1510,10 @@ class SignalReportViewSet(# dropping back to potential. snooze_for is irrelevant here and ignored by transition_to.target_status = SignalReport.Status(target)if report.status == SignalReport.Status.SUPPRESSED and target_status == SignalReport.Status.POTENTIAL:+ # Restore guard: a refunded report can never be billed again (see billing.py), so+ # refund → restore → new PR would be repeatable free work. The refund is final.+ if getattr(report, "refund", None) is not None:+ return SignalReportBulkStateOutcome.SKIPPED, "Refunded reports can't be restored."target_status = report.restore_target_status()effective_snooze_for = snooze_for if target == "potential" else None@@ -1410,10 +1522,10 @@ class SignalReportViewSet(updated_fields = report.transition_to(target_status, snooze_for=effective_snooze_for)except InvalidStatusTransition as e:logger.warning("Invalid status transition for SignalReport %s: %s", report.id, e, exc_info=True)- return SignalReportBulkStateOutcome.SKIPPED+ return SignalReportBulkStateOutcome.SKIPPED, Noneexcept (ValueError, TypeError) as e:logger.warning("Invalid data when transitioning SignalReport %s: %s", report.id, e, exc_info=True)- return SignalReportBulkStateOutcome.FAILED+ return SignalReportBulkStateOutcome.FAILED, Nonewith transaction.atomic():report.save(update_fields=updated_fields)@@ -1445,7 +1557,7 @@ class SignalReportViewSet(# A dismissal (transition into SUPPRESSED) closes the linked implementation PR — handled# centrally by the post_save receiver (receivers.close_pr_when_report_dismissed), so this# method doesn't special-case it. Restore/snooze to "potential" leaves the PR alone.- return SignalReportBulkStateOutcome.TRANSITIONED+ return SignalReportBulkStateOutcome.TRANSITIONED, None@extend_schema(request=SignalReportBulkStateRequestSerializer,@@ -1491,9 +1603,10 @@ class SignalReportViewSet(report = reports_by_id.get(report_id)if report is None:outcome = SignalReportBulkStateOutcome.NOT_FOUND+ detail = Nonereport_status = Noneelse:- outcome = self._transition_report_state(+ outcome, detail = self._transition_report_state(report,target=target,dismissal_reason=dismissal_reason,@@ -1506,7 +1619,7 @@ class SignalReportViewSet("id": report_id,"outcome": outcome.value,"status": report_status,- "detail": self._BULK_STATE_OUTCOME_DETAIL.get(outcome),+ "detail": detail or self._BULK_STATE_OUTCOME_DETAIL.get(outcome),})counts[outcome.value] += 1@@ -1521,6 +1634,224 @@ class SignalReportViewSet(})+ def _signals_pr_refunds_enabled(self) -> bool:+ # Server-side feature gate, keyed on the org (the refund window is the org's billing+ # period). Same call shape as the quota-limiting data-retention flag check.+ return (+ posthoganalytics.feature_enabled(+ SIGNALS_PR_REFUNDS_FEATURE_FLAG,+ str(self.organization.id),+ groups={"organization": str(self.organization.id)},+ group_properties={"organization": {"id": str(self.organization.id)}},+ )+ is True+ )++ def _refund_response(self, refund: SignalReportRefund, *, already_refunded: bool = False) -> Response:+ if already_refunded:+ # SignalReportRefundResponseSerializer reads the attribute; absent it falls back to+ # the field default (False), so only the idempotent-replay path sets it.+ refund.already_refunded = True # type: ignore[attr-defined]+ return Response(SignalReportRefundResponseSerializer(refund).data)++ @validated_request(+ request_serializer=SignalReportRefundRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=SignalReportRefundResponseSerializer,+ description=(+ "The refund (created, or the existing one with already_refunded=true when the "+ "report was refunded before)."+ ),+ ),+ 400: OpenApiResponse(+ description=(+ "Report is not refundable: no billable implementation PR, the PR run is outside "+ "the current billing period, or the report is system-marked never-billable."+ )+ ),+ 404: OpenApiResponse(description="Report not found, or refunds are not enabled for this organization."),+ },+ summary="Refund a report's implementation PR",+ description=(+ "Refund the flat charge for this report's implementation PR and archive the report. "+ "Refunds auto-approve: the charge is either excluded from usage before it is ever "+ "reported to billing (refund on the same UTC day as the PR run) or returned as a Stripe "+ "customer-balance credit on the next invoice. A refunded PR does not count toward the "+ "free monthly PR allowance. One refund per report, ever — repeat calls return the "+ "existing refund with already_refunded=true. The report is archived as part of the "+ "refund (a resolved report stays resolved) and can't be restored afterwards."+ ),+ operation_id="signals_reports_refund_create",+ )+ @action(detail=True, methods=["post"], url_path="refund", required_scopes=["task:write"])+ def refund(self, request: ValidatedRequest, pk=None, **kwargs):+ if not self._signals_pr_refunds_enabled():+ raise NotFound("PR refunds are not enabled for this organization.")++ report = cast(SignalReport, self.get_object())+ data = request.validated_data+ note = data.get("note") or ""+ # Resolved before the locked transaction — a bad X-PostHog-Task-Id header must 400+ # before anything mutates (mirrors the artefact write paths).+ attribution = resolve_request_attribution(request, self.team.id)+ user = cast(User, request.user)++ with transaction.atomic():+ # Row-lock the report so double-clicks serialize (precedent: the Slack suppression+ # flow); the refund OneToOne is the backstop if something bypasses the lock.+ report = cast(+ SignalReport,+ SignalReport.objects.select_for_update().get(id=report.id, team_id=self.team_id),+ )++ existing = getattr(report, "refund", None)+ if existing is not None:+ return self._refund_response(existing, already_refunded=True)++ # Same decision the serializer's `refund_ineligibility_reason` field renders from,+ # so the UI's button state and this endpoint's 400s can never disagree.+ billable_run = first_billable_pr_run(report.id)+ # Computed once and frozen onto the refund row below: the credited-path sync must+ # report the period the refund was accepted in, not whatever period is current when+ # the Celery task eventually reaches billing.+ period_start, period_end = current_billing_period_bounds(self.organization)+ ineligibility = refund_ineligibility_reason(+ has_refund=False, # the idempotent 200 above already handled existing refunds+ billing_exempt=bool(report.billing_exempt_reason),+ billable_run_at=billable_run.created_at if billable_run else None,+ period=(period_start, period_end),+ )+ if ineligibility is not None:+ return Response(+ {"error": _REFUND_INELIGIBLE_MESSAGES[ineligibility]},+ status=status.HTTP_400_BAD_REQUEST,+ )+ assert billable_run is not None # narrowed by the no_billable_pr reason above++ # Freeze the billing path by the UTC-day rule: refunds committed on the PR run's own+ # UTC day land before any usage send covering that day (all sends happen ≥3h45m into+ # the next UTC day), so the report can simply be excluded from usage; anything later+ # must go through a billing-service credit. Decided once, stored, never recomputed.+ now = timezone.now()+ pr_merged = SignalReport.Status.RESOLVED in (report.status, report.status_before_suppression)+ billing_path = (+ SignalReportRefund.BillingPath.EXCLUDED+ if billable_run.created_at.astimezone(UTC).date() == now.astimezone(UTC).date()+ else SignalReportRefund.BillingPath.CREDITED+ )++ try:+ # Savepoint so a unique-constraint loser doesn't poison the outer transaction.+ with transaction.atomic():+ refund = SignalReportRefund.objects.create(+ team_id=report.team_id,+ report=report,+ created_by=user if user.is_authenticated else None,+ reason=data["reason"],+ note=note,+ billing_path=billing_path,+ credits=SIGNALS_CREDITS_PER_REPORT_WITH_PR,+ pr_url=billable_run.pr_url,+ pr_run_created_at=billable_run.created_at,+ period_start=period_start,+ period_end=period_end,+ )+ except IntegrityError:+ existing = SignalReportRefund.objects.filter(report_id=report.id).first()+ if existing is None:+ raise+ return self._refund_response(existing, already_refunded=True)++ # Refund doubles as archive: suppress unless the report is resolved (stays resolved —+ # the merged PR shipped) or already suppressed. The dismissal artefact records the+ # rationale like any other dismissal; the structured truth lives on the refund row.+ if report.status not in (SignalReport.Status.RESOLVED, SignalReport.Status.SUPPRESSED):+ updated_fields = report.transition_to(SignalReport.Status.SUPPRESSED)+ report.save(update_fields=updated_fields)+ SignalReportArtefact.append_dismissal(+ team_id=self.team.id,+ report_id=str(report.id),+ content=Dismissal(+ reason="refunded",+ note=note or None,+ user_id=user.id if user.is_authenticated else None,+ user_uuid=str(user.uuid) if user.is_authenticated else None,+ ),+ attribution=attribution,+ )++ if billing_path == SignalReportRefund.BillingPath.CREDITED:+ refund_id = str(refund.id)+ transaction.on_commit(lambda: sync_signals_refund_credit.delay(refund_id))++ report_user_action(+ user,+ "signals_pr_refund_created",+ properties={+ "team_id": self.team.id,+ "organization_id": str(self.organization.id),+ "report_id": str(report.id),+ "refund_id": str(refund.id),+ "billing_path": billing_path,+ "credits": refund.credits,+ "reason": refund.reason,+ "pr_merged": pr_merged,+ "days_since_pr": (now - billable_run.created_at).days,+ },+ team=self.team,+ organization=self.organization,+ )++ return self._refund_response(refund)++ @extend_schema(+ responses={+ 200: OpenApiResponse(+ response=SignalReportRefundSummaryResponseSerializer,+ description="Org-wide credited-refund totals for the current billing period.",+ ),+ 404: OpenApiResponse(description="Refunds are not enabled for this organization."),+ },+ summary="Summarize credited PR refunds for the billing period",+ description=(+ "Aggregate credited-path refunds across the whole organization for the current billing "+ "period — counts only, no per-team detail. The billing usage widget needs this because "+ "billing usage is org-wide while reports (and their refunds) are team-scoped: subtract "+ "the refunded credits from billing usage to show the net PR count. Excluded-path "+ "refunds never reach billing usage, so no adjustment is needed for them. Also carries "+ "the org's live billable credits for the period (billing's recorded usage lags by up "+ "to a day), so the widget can count just-created PRs and react to same-day refunds."+ ),+ operation_id="signals_reports_refund_summary_retrieve",+ )+ @action(detail=False, methods=["get"], url_path="refund-summary", required_scopes=["task:read"])+ def refund_summary(self, request: Request, **kwargs):+ if not self._signals_pr_refunds_enabled():+ raise NotFound("PR refunds are not enabled for this organization.")++ period_start, period_end = current_billing_period_bounds(self.organization)+ aggregates = (+ # Org-wide on purpose (unscoped + org filter): the usage this offsets is org-level.+ SignalReportRefund.objects.unscoped()+ .filter(+ team__organization_id=self.organization.id,+ billing_path=SignalReportRefund.BillingPath.CREDITED,+ pr_run_created_at__gte=period_start,+ pr_run_created_at__lt=period_end,+ )+ .aggregate(credited_refund_count=Count("id"), credited_credits=Sum("credits"))+ )+ return Response(+ {+ "credited_refund_count": aggregates["credited_refund_count"] or 0,+ "credited_credits": aggregates["credited_credits"] or 0,+ "period_billable_credits": period_billable_credits_for_org(+ self.organization.id, period_start, period_end+ ),+ }+ )+@extend_schema(exclude=True)@action(detail=True, methods=["post"], url_path="reingest", required_scopes=["task:write"])def reingest(self, request, pk=None, **kwargs):diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 635462f038e2..86358abb9125 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -61,6 +61,90 @@ export const SignalReportStatusEnumApi = {Suppressed: 'suppressed',} as const+/**+ * * `pr_incorrect` - PR incorrect+ * * `pr_not_useful` - PR not useful+ * * `duplicate` - Duplicate+ * * `other` - Other+ */+export type SignalReportRefundReasonEnumApi =+ (typeof SignalReportRefundReasonEnumApi)[keyof typeof SignalReportRefundReasonEnumApi]++export const SignalReportRefundReasonEnumApi = {+ PrIncorrect: 'pr_incorrect',+ PrNotUseful: 'pr_not_useful',+ Duplicate: 'duplicate',+ Other: 'other',+} as const++/**+ * * `excluded` - Excluded+ * * `credited` - Credited+ */+export type BillingPathEnumApi = (typeof BillingPathEnumApi)[keyof typeof BillingPathEnumApi]++export const BillingPathEnumApi = {+ Excluded: 'excluded',+ Credited: 'credited',+} as const++export interface SignalReportRefundApi {+ readonly id: string+ /** Why the user refunded this PR (feeds the refund review).+ *+ * * `pr_incorrect` - PR incorrect+ * * `pr_not_useful` - PR not useful+ * * `duplicate` - Duplicate+ * * `other` - Other */+ readonly reason: SignalReportRefundReasonEnumApi+ /** Optional free-form note captured with the refund. */+ readonly note: string+ /** How the refund was executed, frozen at refund time: 'excluded' (same UTC day as the billable PR run — the report never reaches billing) or 'credited' (billing issues a Stripe customer-balance credit).+ *+ * * `excluded` - Excluded+ * * `credited` - Credited */+ readonly billing_path: BillingPathEnumApi+ /** Signals credits refunded (flat per-PR charge snapshot; 1 credit = $0.01). */+ readonly credits: number+ /** The refunded implementation PR's GitHub URL, snapshotted at refund time. */+ readonly pr_url: string+ /** When the first billable PR run was created — the charge this reverses. */+ readonly pr_run_created_at: string+ /**+ * USD amount the billing service credited (credited path only). Null until the sync completes; '0.00' is a legitimate outcome (e.g. the PR was inside the free tier).+ * @nullable+ * @pattern ^-?\d{0,8}(?:\.\d{0,2})?$+ */+ readonly credit_amount_usd: string | null+ /** Whether the billing service has acknowledged this refund. Always relevant for the credited path (the Stripe credit is issued asynchronously); excluded-path refunds need no billing sync and report false. */+ readonly billing_synced: boolean+ /** When the refund was created. */+ readonly created_at: string+}++export type RefundIneligibilityReasonEnumApi =+ (typeof RefundIneligibilityReasonEnumApi)[keyof typeof RefundIneligibilityReasonEnumApi]++export const RefundIneligibilityReasonEnumApi = {+ AlreadyRefunded: 'already_refunded',+ BillingExempt: 'billing_exempt',+ NoBillablePr: 'no_billable_pr',+ OutOfPeriod: 'out_of_period',+} as const++/**+ * * `posthog_health_check` - PostHog health check+ * * `posthog_onboarding` - PostHog onboarding+ * * `posthog_system` - PostHog system+ */+export type BillingExemptReasonEnumApi = (typeof BillingExemptReasonEnumApi)[keyof typeof BillingExemptReasonEnumApi]++export const BillingExemptReasonEnumApi = {+ PosthogHealthCheck: 'posthog_health_check',+ PosthogOnboarding: 'posthog_onboarding',+ PosthogSystem: 'posthog_system',+} as const+export interface SignalReportApi {readonly id: string/** @nullable */@@ -112,6 +196,16 @@ export interface SignalReportApi {* @nullable*/readonly implementation_pr_url: string | null+ /** The report's PR refund, when one exists. One refund per report, ever. */+ readonly refund: SignalReportRefundApi | null+ /** Why refunding this report's PR would be rejected right now, or null when a refund would be accepted (see the field's schema for the reason values). */+ readonly refund_ineligibility_reason: RefundIneligibilityReasonEnumApi | null+ /** Non-null when this report is system-marked never-billable (PostHog-system origin, e.g. a health-check scout finding) — its implementation PRs are free and cannot be refunded because nothing was charged.+ *+ * * `posthog_health_check` - PostHog health check+ * * `posthog_onboarding` - PostHog onboarding+ * * `posthog_system` - PostHog system */+ readonly billing_exempt_reason: BillingExemptReasonEnumApi | null}export interface PaginatedSignalReportListApi {@@ -145,6 +239,57 @@ export interface PatchedSignalReportContentUpdateApi {summary?: string}+export interface SignalReportRefundRequestApi {+ /** Why this PR is being refunded. One of: pr_incorrect (the PR doesn't address what the report promised), pr_not_useful (technically fine but not worth paying for), duplicate (covers work already charged elsewhere), other. Required — refund reviews key on it.+ *+ * * `pr_incorrect` - PR incorrect+ * * `pr_not_useful` - PR not useful+ * * `duplicate` - Duplicate+ * * `other` - Other */+ reason: SignalReportRefundReasonEnumApi+ /**+ * Optional free-form context for the refund; stored on the refund and echoed in the report's dismissal artefact. Capped at 4000 characters.+ * @maxLength 4000+ */+ note?: string+}++export interface SignalReportRefundResponseApi {+ readonly id: string+ /** Why the user refunded this PR (feeds the refund review).+ *+ * * `pr_incorrect` - PR incorrect+ * * `pr_not_useful` - PR not useful+ * * `duplicate` - Duplicate+ * * `other` - Other */+ readonly reason: SignalReportRefundReasonEnumApi+ /** Optional free-form note captured with the refund. */+ readonly note: string+ /** How the refund was executed, frozen at refund time: 'excluded' (same UTC day as the billable PR run — the report never reaches billing) or 'credited' (billing issues a Stripe customer-balance credit).+ *+ * * `excluded` - Excluded+ * * `credited` - Credited */+ readonly billing_path: BillingPathEnumApi+ /** Signals credits refunded (flat per-PR charge snapshot; 1 credit = $0.01). */+ readonly credits: number+ /** The refunded implementation PR's GitHub URL, snapshotted at refund time. */+ readonly pr_url: string+ /** When the first billable PR run was created — the charge this reverses. */+ readonly pr_run_created_at: string+ /**+ * USD amount the billing service credited (credited path only). Null until the sync completes; '0.00' is a legitimate outcome (e.g. the PR was inside the free tier).+ * @nullable+ * @pattern ^-?\d{0,8}(?:\.\d{0,2})?$+ */+ readonly credit_amount_usd: string | null+ /** Whether the billing service has acknowledged this refund. Always relevant for the credited path (the Stripe credit is issued asynchronously); excluded-path refunds need no billing sync and report false. */+ readonly billing_synced: boolean+ /** When the refund was created. */+ readonly created_at: string+ /** True when the report already had a refund and that existing refund is returned unchanged — refunds are one-per-report and repeat calls are idempotent. */+ readonly already_refunded: boolean+}+/*** * `session_replay` - session_replay* * `llm_analytics` - llm_analytics@@ -833,6 +978,15 @@ export interface SignalReportBulkStateResponseApi {not_found_count: number}+export interface SignalReportRefundSummaryResponseApi {+ /** Number of credited-path refunds across the whole organization whose refunded PR run falls in the current billing period. Excluded-path refunds never reach billing usage, so they are deliberately absent. */+ credited_refund_count: number+ /** Total signals credits those refunds returned (1 credit = $0.01). Divide by the flat per-PR charge to get the number of PRs to subtract from billing usage. */+ credited_credits: number+ /** The organization's live billable signals credits for the current billing period, computed by the same rules as the nightly usage report — including PRs created today that billing hasn't recorded yet, and already excluding refund-excluded and billing-exempt reports. Take the max of this and billing's recorded usage for a live PR count that reacts to new PRs and same-day refunds immediately. */+ period_billable_credits: number+}+export type ScoutOriginEnumApi = (typeof ScoutOriginEnumApi)[keyof typeof ScoutOriginEnumApi]export const ScoutOriginEnumApi = {diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 1696d3776bb9..3509e5cd399a 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -43,6 +43,9 @@ import type {SignalReportArtefactWriteResponseApi,SignalReportBulkStateRequestApi,SignalReportBulkStateResponseApi,+ SignalReportRefundRequestApi,+ SignalReportRefundResponseApi,+ SignalReportRefundSummaryResponseApi,SignalReportStateRequestApi,SignalScoutConfigApi,SignalScoutConfigCreateApi,@@ -212,6 +215,28 @@ export const signalsReportsPartialUpdate = async (})}+export const getSignalsReportsRefundCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/reports/${id}/refund/`+}++/**+ * Refund the flat charge for this report's implementation PR and archive the report. Refunds auto-approve: the charge is either excluded from usage before it is ever reported to billing (refund on the same UTC day as the PR run) or returned as a Stripe customer-balance credit on the next invoice. A refunded PR does not count toward the free monthly PR allowance. One refund per report, ever — repeat calls return the existing refund with already_refunded=true. The report is archived as part of the refund (a resolved report stays resolved) and can't be restored afterwards.+ * @summary Refund a report's implementation PR+ */+export const signalsReportsRefundCreate = async (+ projectId: string,+ id: string,+ signalReportRefundRequestApi: SignalReportRefundRequestApi,+ options?: RequestInit+): Promise<SignalReportRefundResponseApi> => {+ return apiMutator<SignalReportRefundResponseApi>(getSignalsReportsRefundCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(signalReportRefundRequestApi),+ })+}+export const getSignalsReportsSignalsRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/signals/reports/${id}/signals/`}@@ -439,6 +464,24 @@ export const signalsReportsBulkStateCreate = async (})}+export const getSignalsReportsRefundSummaryRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/reports/refund-summary/`+}++/**+ * Aggregate credited-path refunds across the whole organization for the current billing period — counts only, no per-team detail. The billing usage widget needs this because billing usage is org-wide while reports (and their refunds) are team-scoped: subtract the refunded credits from billing usage to show the net PR count. Excluded-path refunds never reach billing usage, so no adjustment is needed for them. Also carries the org's live billable credits for the period (billing's recorded usage lags by up to a day), so the widget can count just-created PRs and react to same-day refunds.+ * @summary Summarize credited PR refunds for the billing period+ */+export const signalsReportsRefundSummaryRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<SignalReportRefundSummaryResponseApi> => {+ return apiMutator<SignalReportRefundSummaryResponseApi>(getSignalsReportsRefundSummaryRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsScoutConfigListUrl = (projectId: string) => {return `/api/projects/${projectId}/signals/scout/configs/`}diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex c4d15e41263f..2437f354852a 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -47,6 +47,30 @@ export const SignalsReportsPartialUpdateBody = /* @__PURE__ */ zod'Editable human-facing fields on a signal report (PATCH).\n\nBoth fields are optional so a caller can change either independently, but at least one\nmust be supplied. Every other report field — status, weights, judgments — is owned by the\nsignals pipeline and is deliberately not writable here.')+/**+ * Refund the flat charge for this report's implementation PR and archive the report. Refunds auto-approve: the charge is either excluded from usage before it is ever reported to billing (refund on the same UTC day as the PR run) or returned as a Stripe customer-balance credit on the next invoice. A refunded PR does not count toward the free monthly PR allowance. One refund per report, ever — repeat calls return the existing refund with already_refunded=true. The report is archived as part of the refund (a resolved report stays resolved) and can't be restored afterwards.+ * @summary Refund a report's implementation PR+ */+export const signalsReportsRefundCreateBodyNoteMax = 4000++export const SignalsReportsRefundCreateBody = /* @__PURE__ */ zod.object({+ reason: zod+ .enum(['pr_incorrect', 'pr_not_useful', 'duplicate', 'other'])+ .describe(+ '\* `pr_incorrect` - PR incorrect\n\* `pr_not_useful` - PR not useful\n\* `duplicate` - Duplicate\n\* `other` - Other'+ )+ .describe(+ "Why this PR is being refunded. One of: pr_incorrect (the PR doesn't address what the report promised), pr_not_useful (technically fine but not worth paying for), duplicate (covers work already charged elsewhere), other. Required — refund reviews key on it.\n\n\* `pr_incorrect` - PR incorrect\n\* `pr_not_useful` - PR not useful\n\* `duplicate` - Duplicate\n\* `other` - Other"+ ),+ note: zod+ .string()+ .max(signalsReportsRefundCreateBodyNoteMax)+ .optional()+ .describe(+ "Optional free-form context for the refund; stored on the refund and echoed in the report's dismissal artefact. Capped at 4000 characters."+ ),+})+/*** Transition a report to a new state. The model validates allowed transitions.*diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex f174fe08f6b2..c924ab3da685 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -344,6 +344,12 @@ tools:signals-report-artefacts-diff:operation: signals_report_artefacts_diffenabled: false+ signals-reports-refund-create:+ operation: signals_reports_refund_create+ enabled: false+ signals-reports-refund-summary-retrieve:+ operation: signals_reports_refund_summary_retrieve+ enabled: falsesignals-reports-signals-retrieve:operation: signals_reports_signals_retrieveenabled: falsediff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex d5c94e1d4bb4..de9129563ca6 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -882,6 +882,20 @@ def update_task_run_state(return TaskRun.update_state_atomic(run_id, updates=updates, remove_keys=remove_keys)+def set_task_run_created_at_for_seeding(+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, created_at: datetime+) -> None:+ """Backdate a run's ``created_at`` — DEBUG-only escape hatch for dev seeding.++ Signals' billing/refund seeding needs runs whose billable moment falls on an earlier UTC+ day; ``created_at`` is deliberately not writable through the PATCH surface, so the hatch+ lives here rather than callers reaching into the ORM.+ """+ if not settings.DEBUG:+ raise RuntimeError("set_task_run_created_at_for_seeding is DEBUG-only")+ TaskRun.objects.filter(pk=run_id, task_id=task_id, team_id=team_id).update(created_at=created_at)++def fail_task_run(run_id: str | UUID, error: str, error_type: str | None = None) -> bool:"""Mark a QUEUED run as failed. Returns whether a run was acted on.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4001ebcf60f6..2ed6b469f5d6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12153,6 +12153,32 @@ export namespace Schemas {BigQuery: 'BigQuery',} as const;+ /**+ * * `posthog_health_check` - PostHog health check+ * * `posthog_onboarding` - PostHog onboarding+ * * `posthog_system` - PostHog system+ */+ export type BillingExemptReasonEnum = typeof BillingExemptReasonEnum[keyof typeof BillingExemptReasonEnum];+++ export const BillingExemptReasonEnum = {+ PosthogHealthCheck: 'posthog_health_check',+ PosthogOnboarding: 'posthog_onboarding',+ PosthogSystem: 'posthog_system',+ } as const;++ /**+ * * `excluded` - Excluded+ * * `credited` - Credited+ */+ export type BillingPathEnum = typeof BillingPathEnum[keyof typeof BillingPathEnum];+++ export const BillingPathEnum = {+ Excluded: 'excluded',+ Credited: 'credited',+ } as const;+/*** * `email` - email*/@@ -37559,6 +37585,66 @@ export namespace Schemas {Suppressed: 'suppressed',} as const;+ /**+ * * `pr_incorrect` - PR incorrect+ * * `pr_not_useful` - PR not useful+ * * `duplicate` - Duplicate+ * * `other` - Other+ */+ export type SignalReportRefundReasonEnum = typeof SignalReportRefundReasonEnum[keyof typeof SignalReportRefundReasonEnum];+++ export const SignalReportRefundReasonEnum = {+ PrIncorrect: 'pr_incorrect',+ PrNotUseful: 'pr_not_useful',+ Duplicate: 'duplicate',+ Other: 'other',+ } as const;++ export interface SignalReportRefund {+ readonly id: string;+ /** Why the user refunded this PR (feeds the refund review).+ *+ * * `pr_incorrect` - PR incorrect+ * * `pr_not_useful` - PR not useful+ * * `duplicate` - Duplicate+ * * `other` - Other */+ readonly reason: SignalReportRefundReasonEnum;+ /** Optional free-form note captured with the refund. */+ readonly note: string;+ /** How the refund was executed, frozen at refund time: 'excluded' (same UTC day as the billable PR run — the report never reaches billing) or 'credited' (billing issues a Stripe customer-balance credit).+ *+ * * `excluded` - Excluded+ * * `credited` - Credited */+ readonly billing_path: BillingPathEnum;+ /** Signals credits refunded (flat per-PR charge snapshot; 1 credit = $0.01). */+ readonly credits: number;+ /** The refunded implementation PR's GitHub URL, snapshotted at refund time. */+ readonly pr_url: string;+ /** When the first billable PR run was created — the charge this reverses. */+ readonly pr_run_created_at: string;+ /**+ * USD amount the billing service credited (credited path only). Null until the sync completes; '0.00' is a legitimate outcome (e.g. the PR was inside the free tier).+ * @nullable+ * @pattern ^-?\d{0,8}(?:\.\d{0,2})?$+ */+ readonly credit_amount_usd: string | null;+ /** Whether the billing service has acknowledged this refund. Always relevant for the credited path (the Stripe credit is issued asynchronously); excluded-path refunds need no billing sync and report false. */+ readonly billing_synced: boolean;+ /** When the refund was created. */+ readonly created_at: string;+ }++ export type RefundIneligibilityReasonEnum = typeof RefundIneligibilityReasonEnum[keyof typeof RefundIneligibilityReasonEnum];+++ export const RefundIneligibilityReasonEnum = {+ AlreadyRefunded: 'already_refunded',+ BillingExempt: 'billing_exempt',+ NoBillablePr: 'no_billable_pr',+ OutOfPeriod: 'out_of_period',+ } as const;+export interface SignalReport {readonly id: string;/** @nullable */@@ -37610,6 +37696,16 @@ export namespace Schemas {* @nullable*/readonly implementation_pr_url: string | null;+ /** The report's PR refund, when one exists. One refund per report, ever. */+ readonly refund: SignalReportRefund | null;+ /** Why refunding this report's PR would be rejected right now, or null when a refund would be accepted (see the field's schema for the reason values). */+ readonly refund_ineligibility_reason: RefundIneligibilityReasonEnum | null;+ /** Non-null when this report is system-marked never-billable (PostHog-system origin, e.g. a health-check scout finding) — its implementation PRs are free and cannot be refunded because nothing was charged.+ *+ * * `posthog_health_check` - PostHog health check+ * * `posthog_onboarding` - PostHog onboarding+ * * `posthog_system` - PostHog system */+ readonly billing_exempt_reason: BillingExemptReasonEnum | null;}export interface PaginatedSignalReportList {@@ -53958,6 +54054,66 @@ export namespace Schemas {not_found_count: number;}+ export interface SignalReportRefundRequest {+ /** Why this PR is being refunded. One of: pr_incorrect (the PR doesn't address what the report promised), pr_not_useful (technically fine but not worth paying for), duplicate (covers work already charged elsewhere), other. Required — refund reviews key on it.+ *+ * * `pr_incorrect` - PR incorrect+ * * `pr_not_useful` - PR not useful+ * * `duplicate` - Duplicate+ * * `other` - Other */+ reason: SignalReportRefundReasonEnum;+ /**+ * Optional free-form context for the refund; stored on the refund and echoed in the report's dismissal artefact. Capped at 4000 characters.+ * @maxLength 4000+ */+ note?: string;+ }++ export interface SignalReportRefundResponse {+ readonly id: string;+ /** Why the user refunded this PR (feeds the refund review).+ *+ * * `pr_incorrect` - PR incorrect+ * * `pr_not_useful` - PR not useful+ * * `duplicate` - Duplicate+ * * `other` - Other */+ readonly reason: SignalReportRefundReasonEnum;+ /** Optional free-form note captured with the refund. */+ readonly note: string;+ /** How the refund was executed, frozen at refund time: 'excluded' (same UTC day as the billable PR run — the report never reaches billing) or 'credited' (billing issues a Stripe customer-balance credit).+ *+ * * `excluded` - Excluded+ * * `credited` - Credited */+ readonly billing_path: BillingPathEnum;+ /** Signals credits refunded (flat per-PR charge snapshot; 1 credit = $0.01). */+ readonly credits: number;+ /** The refunded implementation PR's GitHub URL, snapshotted at refund time. */+ readonly pr_url: string;+ /** When the first billable PR run was created — the charge this reverses. */+ readonly pr_run_created_at: string;+ /**+ * USD amount the billing service credited (credited path only). Null until the sync completes; '0.00' is a legitimate outcome (e.g. the PR was inside the free tier).+ * @nullable+ * @pattern ^-?\d{0,8}(?:\.\d{0,2})?$+ */+ readonly credit_amount_usd: string | null;+ /** Whether the billing service has acknowledged this refund. Always relevant for the credited path (the Stripe credit is issued asynchronously); excluded-path refunds need no billing sync and report false. */+ readonly billing_synced: boolean;+ /** When the refund was created. */+ readonly created_at: string;+ /** True when the report already had a refund and that existing refund is returned unchanged — refunds are one-per-report and repeat calls are idempotent. */+ readonly already_refunded: boolean;+ }++ export interface SignalReportRefundSummaryResponse {+ /** Number of credited-path refunds across the whole organization whose refunded PR run falls in the current billing period. Excluded-path refunds never reach billing usage, so they are deliberately absent. */+ credited_refund_count: number;+ /** Total signals credits those refunds returned (1 credit = $0.01). Divide by the flat per-PR charge to get the number of PRs to subtract from billing usage. */+ credited_credits: number;+ /** The organization's live billable signals credits for the current billing period, computed by the same rules as the nightly usage report — including PRs created today that billing hasn't recorded yet, and already excluding refund-excluded and billing-exempt reports. Take the max of this and billing's recorded usage for a live PR count that reacts to new PRs and same-day refunds immediately. */+ period_billable_credits: number;+ }+export interface SignalReportStateRequest {/** Target state for the report. Use 'suppressed' to dismiss the report from the inbox, or 'potential' to snooze/reopen it for later review.*