:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): index the billable PR run scan off the run output JSONB (#103451)
posthog[bot]dc5e1899022b
diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.pyindex 67c07aec327c..56e228c480f3 100644--- a/products/signals/backend/billing.py+++ b/products/signals/backend/billing.py@@ -53,17 +53,13 @@ from products.signals.backend.enums import SignalSourceProductfrom products.signals.backend.models import SignalReport, SignalReportRefund, SignalReportTask, SignalScoutRunfrom products.signals.backend.scout_harness.lazy_seed import scout_skill_row_is_proven_canonicalfrom products.skills.backend.models.skills import LLMSkill+from products.tasks.backend.facade.api import GITHUB_PR_URL_PREFIXif TYPE_CHECKING:from posthog.models.organization import Organization_IMPLEMENTATION = TASK_RUN_TYPE_IMPLEMENTATION-# Only PRs hosted on GitHub are billable. The PR URL is GitHub's `html_url`-# (https://github.com/owner/repo/pull/N), so validate the host prefix to avoid charging-# for malformed or non-GitHub values written into `output.pr_url`.-_GITHUB_PR_URL_PREFIX = "https://github.com/"-SIGNALS_CREDITS_PER_DOLLAR = 100 # 1 credit = $0.01, matching ai_credits# Flat credits charged once per report whose implementation shipped a PR ($15).@@ -77,17 +73,21 @@ def _bridges_with_pr_run(**run_created_at: datetime) -> QuerySet[SignalReportTas`task__runs` relation, so the query never imports the tasks product's internals — it staysbehind the tasks public interface. Postgres is free to drive the join from the run`created_at` index regardless, so the period scan stays bounded by PRs shipped, not by the- number of bridges.+ number of bridges. `task_run_github_pr_run_idx` keeps that scan off the runs' `output` JSONB,+ but only while the prefix test here stays spelled as the `GITHUB_PR_URL_PREFIX` its predicate+ was built from.Fail closed: a bridge only counts when one of its runs carries a GitHub PR URL within thegiven `created_at` bound and the four teams in the chain — run, task, bridge, and report —- all agree. A malformed bridge whose teams disagree is excluded rather than charged to- whichever team_id happened to be on it. The run-level conditions sit in one `filter()` so- they all resolve against the same `TaskRun` row.+ all agree. Only GitHub is billable, because the URL is GitHub's `html_url`, so the host+ prefix test keeps malformed values written into `output.pr_url` from raising a charge. A+ malformed bridge whose teams disagree is excluded rather than charged to whichever team_id+ happened to be on it. The run-level conditions sit in one `filter()` so they all resolve+ against the same `TaskRun` row."""return SignalReportTask.objects.filter(relationship=_IMPLEMENTATION,- task__runs__output__pr_url__startswith=_GITHUB_PR_URL_PREFIX,+ task__runs__output__pr_url__startswith=GITHUB_PR_URL_PREFIX,# Fail closed on team disagreement across run / task / bridge / report.task__team_id=F("team_id"),report__team_id=F("team_id"),diff --git a/products/signals/backend/test/test_billing.py b/products/signals/backend/test/test_billing.pyindex 81cc90516045..7552c9b381f8 100644--- a/products/signals/backend/test/test_billing.py+++ b/products/signals/backend/test/test_billing.py@@ -14,6 +14,7 @@ from products.signals.backend.billing import (SIGNALS_CREDITS_PER_REPORT_WITH_PR,BillingExemptionError,FirstBillablePrRun,+ _bridges_with_pr_run,first_billable_pr_run,get_signals_billing_credits_by_team,mark_report_billing_exempt,@@ -401,6 +402,18 @@ class TestSignalsBilling(BaseTest):def test_no_billable_reports_returns_empty(self) -> None:self.assertEqual(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END), [])+ def test_pr_url_filter_repeats_the_partial_index_predicate(self) -> None:+ # Postgres answers the prefix test from `task_run_github_pr_run_idx` only while the query+ # spells the predicate the same way. A changed prefix or lookup here still returns the+ # right credits, so nothing else fails — the period scan just goes back to detoasting+ # every run's `output`.+ run_model = _task_run_model()+ index = next(i for i in run_model._meta.indexes if i.name == "task_run_github_pr_run_idx")+ index_sql, index_params = run_model.objects.filter(index.condition).order_by().query.sql_with_params()+ query_sql, query_params = _bridges_with_pr_run().query.sql_with_params()+ self.assertIn(index_sql.split(" WHERE ", 1)[1], query_sql)+ self.assertTrue(set(index_params).issubset(query_params))+class TestBillingExemptions(BaseTest):def test_mark_report_billing_exempt_sets_reason_before_billable_run(self) -> None:diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 3a2949e9ce08..bec78bf4f1ff 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -13,6 +13,12 @@ from products.tasks.backend import model_catalogPR_STATES = ("open", "draft", "merged", "closed")CI_STATUSES = ("passing", "failing", "pending", "none")+# Host prefix of the PR URLs written to ``TaskRun.output['pr_url']`` — GitHub's ``html_url``.+# ``task_run_github_pr_run_idx`` is a partial index on exactly this prefix test, and Postgres only+# skips the JSONB scan while a query repeats the predicate verbatim, so readers filtering on the+# prefix must use this constant rather than a literal of their own.+GITHUB_PR_URL_PREFIX = "https://github.com/"+SANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"WORKFLOW_DISPATCH_SHADOW_FEATURE_FLAG = "tasks-workflow-dispatch-shadow"WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG = "tasks-workflow-dispatch-async"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex a9f62f7a8119..4d734e82050b 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -71,6 +71,7 @@ from products.tasks.backend.constants import (CI_STATUSES as CI_STATUSES, # re-exported for presentationDEV_STACK_PREVIEW_PORT,DEV_STACK_PREVIEW_STATE_KEY,+ GITHUB_PR_URL_PREFIX as GITHUB_PR_URL_PREFIX, # re-exported for signals billingMAX_CUSTOM_IMAGES_PER_TEAM,MAX_CUSTOM_IMAGES_PER_USER,PR_LOOP_ENABLED_STATE_KEY,@@ -2941,7 +2942,7 @@ def _refresh_self_driving_quota_for_pr(run: TaskRun, old_pr_url: str | None) -># recompute for any other output.pr_url string is a guaranteed no-op; don't let arbitrary# client-written values enqueue org-wide refreshes. Literal kept local because tasks code# must not import signals internals.- if not new_pr_url.startswith("https://github.com/"):+ if not new_pr_url.startswith(GITHUB_PR_URL_PREFIX):returnorganization_id = Team.objects.filter(id=run.task.team_id).values_list("organization_id", flat=True).first()if organization_id is None:diff --git a/products/tasks/backend/migrations/0131_taskrun_github_pr_run_idx.py b/products/tasks/backend/migrations/0131_taskrun_github_pr_run_idx.pynew file mode 100644index 000000000000..8ac94195567f--- /dev/null+++ b/products/tasks/backend/migrations/0131_taskrun_github_pr_run_idx.py@@ -0,0 +1,22 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("tasks", "0130_remove_twd_claimed_lease_idx"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="taskrun",+ index=models.Index(+ fields=["created_at"],+ name="task_run_github_pr_run_idx",+ condition=models.Q(output__pr_url__startswith="https://github.com/"),+ ),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 2f655a92bb54..1190cd4390f8 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0130_remove_twd_claimed_lease_idx+0131_taskrun_github_pr_run_idxdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex b0f11da643b4..e93030ce893b 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -41,7 +41,7 @@ from posthog.storage import object_storagefrom posthog.temporal.oauth import PosthogMcpScopesfrom posthog.uuidt import uuid7-from products.tasks.backend.constants import DEFAULT_TRUSTED_DOMAINS, PR_LOOP_ENABLED_STATE_KEY+from products.tasks.backend.constants import DEFAULT_TRUSTED_DOMAINS, GITHUB_PR_URL_PREFIX, PR_LOOP_ENABLED_STATE_KEYfrom products.tasks.backend.error_telemetry import truncate_error_messagefrom products.tasks.backend.feature_flags import (is_task_run_stream_presence_gated,@@ -2407,6 +2407,15 @@ class TaskRun(models.Model):# Time-range scans over runs (default ordering, recent-runs lookups, and the# signals outcome-billing query that buckets PR runs into a period).models.Index(fields=["created_at"], name="task_run_created_at_idx"),+ # The same period scan, narrowed to runs that shipped a GitHub PR. A prefix match+ # cannot use `task_run_output_pr_url_idx`, so on `task_run_created_at_idx` alone+ # Postgres detoasts every run's `output` in the window to test it. Carrying the+ # test as the index predicate answers it from the index instead.+ models.Index(+ fields=["created_at"],+ name="task_run_github_pr_run_idx",+ condition=models.Q(output__pr_url__startswith=GITHUB_PR_URL_PREFIX),+ ),models.Index(fields=["task", "-created_at", "-id"], name="task_run_task_created_idx"),models.Index(fields=["team", "stage", "task"],diff --git a/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.py b/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.pyindex 6829b9c8846d..80880155ae30 100644--- a/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.py+++ b/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.py@@ -11,6 +11,7 @@ from products.signals.backend.quota import (record_quota_check_failed_open,self_driving_quota_gate,)+from products.tasks.backend.constants import GITHUB_PR_URL_PREFIXfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.temporal.observability import log_with_activity_context@@ -26,18 +27,14 @@ SELF_DRIVING_QUOTA_CANCEL_REASON = ("Stopped automatically: the organization reached its self-driving pull request limit.")-# Only GitHub-hosted PR URLs are billable (products/signals/backend/billing.py applies the same-# prefix rule), so only they attest already-billed work. Run output is caller-writable, which-# means any other pr_url value must not stop enforcement. Literal kept local because tasks code-# must not import signals internals.-_BILLABLE_PR_URL_PREFIX = "https://github.com/"-+# Only GitHub-hosted PR URLs are billable, so only they attest already-billed work. Run output is+# caller-writable, which means any other pr_url value must not stop enforcement.def _has_billable_pr_url(output: object) -> bool:if not isinstance(output, dict):return Falsepr_url = output.get("pr_url")- return isinstance(pr_url, str) and pr_url.startswith(_BILLABLE_PR_URL_PREFIX)+ return isinstance(pr_url, str) and pr_url.startswith(GITHUB_PR_URL_PREFIX)@dataclass