: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
chore(cdp): add rerun_google_ads_failed_invocations management command (#67699)
Meikel Ratz01dc48e4374f
diff --git a/posthog/management/commands/rerun_google_ads_failed_invocations.py b/posthog/management/commands/rerun_google_ads_failed_invocations.pynew file mode 100644index 000000000000..f0605f024244--- /dev/null+++ b/posthog/management/commands/rerun_google_ads_failed_invocations.py@@ -0,0 +1,213 @@+"""+Trigger reruns of failed invocations for every active Google Ads+destination across every team.++Written for the 2026-07-02 incident where Google Ads returned 401+UNAUTHENTICATED (`DEVELOPER_TOKEN_INVALID`) for every send, surfaced on+our side as `error_kind='http_4xx'`. Once operators have swapped the+developer token, this replays the failed sends by triggering the same+"Rerun failed invocations" action the UI's Runs tab would trigger —+scoped to `status=failed` and `error_kind=http_4xx` — for each affected+hog function.++Reruns run asynchronously on `cdp-rerun-worker`; this command only+enqueues one wrapper job per hog function and reports which teams they+were enqueued for.+"""++import time+from datetime import UTC, datetime, timedelta+from typing import Any++from django.core.management.base import BaseCommand, CommandError++from posthog.plugins.plugin_server_api import rerun_hog_invocations++from products.cdp.backend.models.hog_functions.hog_function import HogFunction++GOOGLE_ADS_TEMPLATE_ID = "template-google-ads"+DEFAULT_ERROR_KIND = "http_4xx"++# Matches RERUN_MAX_WINDOW_DAYS in posthog/api/hog_invocation_rerun.py, which+# is the ClickHouse TTL on hog_invocation_results. Anything past this either+# 400s downstream or silently under-replays because the partitions are gone.+MAX_WINDOW_DAYS = 30+++class Command(BaseCommand):+ help = (+ "Rerun failed invocations for every active Google Ads destination. "+ "Filters by status=failed + --error-kind (default http_4xx). Prints "+ "per-function results and a summary."+ )++ def add_arguments(self, parser):+ parser.add_argument(+ "--window-start",+ required=True,+ help="Inclusive ISO-8601 UTC lower bound (e.g. 2026-07-02T00:00:00Z).",+ )+ parser.add_argument(+ "--window-end",+ required=True,+ help="Exclusive ISO-8601 UTC upper bound. Max 30d window (ClickHouse TTL on hog_invocation_results).",+ )+ parser.add_argument(+ "--error-kind",+ action="append",+ default=None,+ help=f"Repeatable. Default: [{DEFAULT_ERROR_KIND}].",+ )+ parser.add_argument(+ "--max-count",+ type=int,+ default=None,+ help="Per-function cap. Server-side hard cap still applies.",+ )+ parser.add_argument(+ "--team-ids",+ nargs="+",+ type=int,+ default=None,+ help="Restrict to specific team IDs (default: every team with an active Google Ads destination).",+ )+ parser.add_argument(+ "--sleep-seconds",+ type=float,+ default=0.0,+ help="Delay between rerun requests. Spreads load if rerun queue depth spikes.",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="List which hog functions would be rerun without triggering the reruns.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ window_start = _parse_iso(options["window_start"], "window-start")+ window_end = _parse_iso(options["window_end"], "window-end")+ if window_end <= window_start:+ raise CommandError("--window-end must be after --window-start.")+ if window_end - window_start > timedelta(days=MAX_WINDOW_DAYS):+ span_days = (window_end - window_start).days+ raise CommandError(+ f"Window cannot exceed {MAX_WINDOW_DAYS} days (ClickHouse TTL on hog_invocation_results). "+ f"Got {span_days} days."+ )++ error_kinds = options["error_kind"] or [DEFAULT_ERROR_KIND]+ dry_run: bool = options["dry_run"]+ sleep_seconds: float = options["sleep_seconds"]+ max_count: int | None = options.get("max_count")+ team_ids: list[int] | None = options.get("team_ids")++ qs = HogFunction.objects.filter(+ template_id=GOOGLE_ADS_TEMPLATE_ID,+ type="destination",+ enabled=True,+ deleted=False,+ ).select_related("team")+ if team_ids:+ qs = qs.filter(team_id__in=team_ids)+ qs = qs.order_by("team_id", "id")++ total = qs.count()+ if total == 0:+ self.stdout.write(self.style.WARNING("No active Google Ads destinations matched."))+ return++ distinct_teams = qs.values("team_id").distinct().count()+ self.stdout.write(f"Found {total} active Google Ads destinations across {distinct_teams} teams.")+ self.stdout.write(+ f"Window: {window_start.isoformat()} → {window_end.isoformat()} "+ f"error_kind={error_kinds} status=[failed]"+ )+ if dry_run:+ self.stdout.write(self.style.WARNING("DRY RUN — no rerun requests will be sent."))++ filter_payload: dict[str, Any] = {+ "window_start": window_start.isoformat(),+ "window_end": window_end.isoformat(),+ "status": ["failed"],+ "error_kind": error_kinds,+ }+ if max_count is not None:+ filter_payload["max_count"] = max_count+ payload = {"filter": filter_payload}++ started = time.time()+ enqueued = 0+ failures: list[tuple[int, str, int, str]] = [] # (team_id, function_id, status, message)+ status_counts: dict[int, int] = {}++ for fn in qs.iterator(chunk_size=200):+ team_id = fn.team_id+ org_id = fn.team.organization_id if fn.team_id else None+ fn_id = str(fn.id)+ label = f"team={team_id} org={org_id} function={fn_id} ({fn.name!r})"++ if dry_run:+ self.stdout.write(f" [dry-run] would rerun {label}")+ enqueued += 1+ continue++ try:+ res = rerun_hog_invocations(+ team_id=team_id,+ function_kind="hog_function",+ function_id=fn_id,+ payload=payload,+ )+ except Exception as e:+ failures.append((team_id, fn_id, 0, f"exception: {e!r}"))+ status_counts[0] = status_counts.get(0, 0) + 1+ self.stdout.write(self.style.ERROR(f" ✗ {label}: exception {e!r}"))+ if sleep_seconds > 0:+ time.sleep(sleep_seconds)+ continue++ status_counts[res.status_code] = status_counts.get(res.status_code, 0) + 1++ if res.status_code != 200:+ failures.append((team_id, fn_id, res.status_code, res.text[:200]))+ self.stdout.write(self.style.ERROR(f" ✗ {label}: HTTP {res.status_code}: {res.text[:200]}"))+ if sleep_seconds > 0:+ time.sleep(sleep_seconds)+ continue++ try:+ body = res.json()+ except ValueError:+ body = {}+ rerun_job_id = body.get("rerun_job_id", "?")+ enqueued += 1+ self.stdout.write(f" ✓ {label}: rerun_job_id={rerun_job_id}")++ if sleep_seconds > 0:+ time.sleep(sleep_seconds)++ duration = time.time() - started+ enqueued_label = "WouldEnqueue" if dry_run else "Enqueued"+ self.stdout.write("")+ self.stdout.write(+ self.style.SUCCESS(+ f"Done in {duration:.1f}s. Destinations={total} | {enqueued_label}={enqueued} | Failed={len(failures)}"+ )+ )+ if status_counts:+ breakdown = ", ".join(f"{code}: {count}" for code, count in sorted(status_counts.items()))+ self.stdout.write(f"HTTP status breakdown: {breakdown}")+ if failures:+ self.stdout.write(self.style.WARNING(f"{len(failures)} rerun request(s) failed:"))+ for team_id, fn_id, status_code, msg in failures:+ self.stdout.write(f" team={team_id} function={fn_id} status={status_code} :: {msg}")+++def _parse_iso(raw: str, arg_name: str) -> datetime:+ try:+ dt = datetime.fromisoformat(raw)+ except ValueError as e:+ raise CommandError(f"--{arg_name}: could not parse ISO-8601 datetime {raw!r}: {e}")+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=UTC)+ return dt.astimezone(UTC)diff --git a/posthog/management/commands/test/test_rerun_google_ads_failed_invocations.py b/posthog/management/commands/test/test_rerun_google_ads_failed_invocations.pynew file mode 100644index 000000000000..526556b1f86e--- /dev/null+++ b/posthog/management/commands/test/test_rerun_google_ads_failed_invocations.py@@ -0,0 +1,110 @@+from io import StringIO++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.core.management import call_command++from products.cdp.backend.models.hog_functions.hog_function import HogFunction++RERUN_HELPER = "posthog.management.commands.rerun_google_ads_failed_invocations.rerun_hog_invocations"+++def _ok_response(rerun_job_id: str = "job-123") -> MagicMock:+ response = MagicMock()+ response.status_code = 200+ response.json.return_value = {"rerun_job_id": rerun_job_id, "queued_count": 0, "skipped_count": 0}+ return response+++def _error_response(status_code: int = 500, text: str = "boom") -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.text = text+ return response+++class TestRerunGoogleAdsFailedInvocations(BaseTest):+ def setUp(self):+ super().setUp()+ # `HogFunction.save()` fires a reload signal that would try to talk to the CDP+ # API; silence it for the whole class so fixtures don't require the network.+ patcher = patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")+ patcher.start()+ self.addCleanup(patcher.stop)++ def _make_fn(self, *, template_id: str, enabled: bool, deleted: bool, name: str = "gads") -> HogFunction:+ return HogFunction.objects.create(+ team=self.team,+ name=name,+ type="destination",+ template_id=template_id,+ enabled=enabled,+ deleted=deleted,+ )++ def test_only_targets_active_non_deleted_google_ads_destinations(self):+ # Regression this catches: if someone drops `enabled=True` or `deleted=False`+ # from the queryset, we'd fire rerun requests at destinations the customer has+ # intentionally turned off (or worse, deleted) after the outage. Also asserts+ # the rerun payload carries status=[failed] + error_kind=[http_4xx] — without+ # both, this command would replay every historical Google Ads send in the+ # window, not just the ones that hit the 401 during the incident.+ target = self._make_fn(template_id="template-google-ads", enabled=True, deleted=False, name="active-gads")+ self._make_fn(template_id="template-google-ads", enabled=False, deleted=False, name="disabled-gads")+ self._make_fn(template_id="template-google-ads", enabled=True, deleted=True, name="deleted-gads")+ self._make_fn(template_id="template-meta-ads", enabled=True, deleted=False, name="not-google")++ with patch(RERUN_HELPER, return_value=_ok_response()) as mock_rerun:+ call_command(+ "rerun_google_ads_failed_invocations",+ "--window-start=2026-07-02T00:00:00Z",+ "--window-end=2026-07-02T12:00:00Z",+ stdout=StringIO(),+ )++ mock_rerun.assert_called_once()+ kwargs = mock_rerun.call_args.kwargs+ self.assertEqual(kwargs["team_id"], target.team_id)+ self.assertEqual(kwargs["function_kind"], "hog_function")+ self.assertEqual(kwargs["function_id"], str(target.id))++ payload_filter = kwargs["payload"]["filter"]+ self.assertEqual(payload_filter["status"], ["failed"])+ self.assertEqual(payload_filter["error_kind"], ["http_4xx"])+ self.assertEqual(payload_filter["window_start"], "2026-07-02T00:00:00+00:00")+ self.assertEqual(payload_filter["window_end"], "2026-07-02T12:00:00+00:00")++ def test_dry_run_does_not_call_rerun_endpoint(self):+ # Regression this catches: --dry-run silently firing real requests would+ # trigger an unintended production rerun during incident-response+ # rehearsal or verification of the target set.+ self._make_fn(template_id="template-google-ads", enabled=True, deleted=False)++ with patch(RERUN_HELPER) as mock_rerun:+ call_command(+ "rerun_google_ads_failed_invocations",+ "--window-start=2026-07-02T00:00:00Z",+ "--window-end=2026-07-02T12:00:00Z",+ "--dry-run",+ stdout=StringIO(),+ )++ mock_rerun.assert_not_called()++ def test_continues_when_one_request_fails(self):+ # Regression this catches: an early 500 from the plugin server halting+ # the whole batch would strand every subsequent team un-retried. The+ # command must call all N destinations regardless.+ self._make_fn(template_id="template-google-ads", enabled=True, deleted=False, name="fn-a")+ self._make_fn(template_id="template-google-ads", enabled=True, deleted=False, name="fn-b")++ with patch(RERUN_HELPER, side_effect=[_error_response(500, "boom"), _ok_response("job-b")]) as mock_rerun:+ call_command(+ "rerun_google_ads_failed_invocations",+ "--window-start=2026-07-02T00:00:00Z",+ "--window-end=2026-07-02T12:00:00Z",+ stdout=StringIO(),+ )++ self.assertEqual(mock_rerun.call_count, 2)diff --git a/posthog/templates/admin/cdp/hogfunction/change_list.html b/posthog/templates/admin/cdp/hogfunction/change_list.htmlnew file mode 100644index 000000000000..cf29e2c5a56a--- /dev/null+++ b/posthog/templates/admin/cdp/hogfunction/change_list.html@@ -0,0 +1,11 @@+{% extends "admin/change_list.html" %}+{% load i18n admin_urls %}++{% block object-tools-items %}+ {% if show_rerun_google_ads_button %}+ <li>+ <a href="{% url 'admin:rerun-google-ads-failed-invocations' %}">Rerun Google Ads failed invocations</a>+ </li>+ {% endif %}+ {{ block.super }}+{% endblock %}diff --git a/posthog/templates/admin/cdp/hogfunction/rerun_google_ads.html b/posthog/templates/admin/cdp/hogfunction/rerun_google_ads.htmlnew file mode 100644index 000000000000..36a1fe568fd1--- /dev/null+++ b/posthog/templates/admin/cdp/hogfunction/rerun_google_ads.html@@ -0,0 +1,40 @@+{% extends "admin/base_site.html" %}+{% load i18n admin_urls %}++{% block content %}+<div id="content-main">+ <p>+ Triggers reruns of failed invocations for every active+ <code>template-google-ads</code> destination in the database. The+ rerun runs asynchronously on <code>cdp-rerun-worker</code>; this form+ only enqueues one wrapper job per hog function and reports which+ teams they were enqueued for.+ </p>+ <p>+ Leave <em>Dry run</em> checked for the first submission to preview+ the target set. Uncheck to actually fire the reruns.+ </p>+ <form method="post">+ {% csrf_token %}+ <fieldset class="module aligned">+ {% for field in form %}+ <div class="form-row">+ {{ field.errors }}+ {{ field.label_tag }} {{ field }}+ {% if field.help_text %}+ <div class="help">{{ field.help_text }}</div>+ {% endif %}+ </div>+ {% endfor %}+ </fieldset>+ <div class="submit-row">+ <input type="submit" value="Run" class="default" name="_run">+ </div>+ </form>++ {% if output %}+ <h2>Output</h2>+ <pre style="background:#f8f8f8;border:1px solid #ddd;padding:12px;overflow:auto;max-height:600px;white-space:pre-wrap;">{{ output }}</pre>+ {% endif %}+</div>+{% endblock %}diff --git a/products/cdp/backend/admin/hog_function_admin.py b/products/cdp/backend/admin/hog_function_admin.pyindex 1c825b2e445e..3b0a80eb7210 100644--- a/products/cdp/backend/admin/hog_function_admin.py+++ b/products/cdp/backend/admin/hog_function_admin.py@@ -1,8 +1,15 @@+from datetime import timedelta+from io import StringIO+from django import forms-from django.contrib import admin-from django.urls import reverse+from django.contrib import admin, messages+from django.core.management import call_command+from django.shortcuts import render+from django.urls import path, reversefrom django.utils.html import format_html+from posthog.management.commands.rerun_google_ads_failed_invocations import MAX_WINDOW_DAYS+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionState@@ -20,9 +27,71 @@ class HogFunctionAdminForm(forms.ModelForm):self.fields["state"].initial = instance.status["state"]+class RerunGoogleAdsFailedInvocationsForm(forms.Form):+ """Admin-facing wrapper around the `rerun_google_ads_failed_invocations`+ management command. Mirrors its CLI flags one-for-one so a follow-up rerun+ from the shell produces the same result."""++ window_start = forms.DateTimeField(+ help_text="Inclusive lower bound on invocation scheduled_at (UTC). E.g. 2026-07-02 00:00:00.",+ )+ window_end = forms.DateTimeField(+ help_text="Exclusive upper bound (max 30d window — matches the ClickHouse TTL on hog_invocation_results).",+ )+ error_kinds = forms.CharField(+ required=False,+ initial="http_4xx",+ help_text="Comma-separated. Defaults to http_4xx.",+ )+ max_count = forms.IntegerField(+ required=False,+ min_value=1,+ help_text="Optional per-function cap. Server-side hard cap still applies.",+ )+ team_ids = forms.CharField(+ required=False,+ help_text="Optional comma-separated team IDs to restrict the run.",+ )+ dry_run = forms.BooleanField(+ required=False,+ initial=True,+ help_text="Preview which hog functions would be targeted, without firing rerun requests.",+ )++ def clean_error_kinds(self) -> list[str]:+ raw = self.cleaned_data.get("error_kinds", "") or ""+ parts = [part.strip() for part in raw.split(",") if part.strip()]+ return parts or ["http_4xx"]++ def clean_team_ids(self) -> list[int]:+ raw = self.cleaned_data.get("team_ids", "") or ""+ if not raw.strip():+ return []+ try:+ return [int(part.strip()) for part in raw.split(",") if part.strip()]+ except ValueError:+ raise forms.ValidationError("Team IDs must be a comma-separated list of integers.")++ def clean(self):+ cleaned = super().clean() or {}+ start = cleaned.get("window_start")+ end = cleaned.get("window_end")+ if start and end:+ if end <= start:+ raise forms.ValidationError("window_end must be after window_start.")+ if end - start > timedelta(days=MAX_WINDOW_DAYS):+ span_days = (end - start).days+ raise forms.ValidationError(+ f"Window cannot exceed {MAX_WINDOW_DAYS} days "+ f"(ClickHouse TTL on hog_invocation_results). Got {span_days} days."+ )+ return cleaned++@admin.register(HogFunction)class HogFunctionAdmin(admin.ModelAdmin):form = HogFunctionAdminForm+ change_list_template = "admin/cdp/hogfunction/change_list.html"list_select_related = ("team",)list_display = ("id", "name", "enabled")list_filter = (@@ -73,3 +142,58 @@ class HogFunctionAdmin(admin.ModelAdmin):if "state" in form.changed_data:state = int(form.cleaned_data["state"])obj.set_function_status(state)++ def get_urls(self):+ custom_urls = [+ path(+ "rerun-google-ads-failed-invocations/",+ self.admin_site.admin_view(self.rerun_google_ads_view),+ name="rerun-google-ads-failed-invocations",+ ),+ ]+ return custom_urls + super().get_urls()++ def changelist_view(self, request, extra_context=None):+ extra_context = extra_context or {}+ extra_context["show_rerun_google_ads_button"] = True+ return super().changelist_view(request, extra_context=extra_context)++ def rerun_google_ads_view(self, request):+ output: str | None = None+ if request.method == "POST":+ form = RerunGoogleAdsFailedInvocationsForm(request.POST)+ if form.is_valid():+ args = [+ f"--window-start={form.cleaned_data['window_start'].isoformat()}",+ f"--window-end={form.cleaned_data['window_end'].isoformat()}",+ ]+ for kind in form.cleaned_data["error_kinds"]:+ args.append(f"--error-kind={kind}")+ if form.cleaned_data.get("max_count") is not None:+ args.append(f"--max-count={form.cleaned_data['max_count']}")+ team_ids = form.cleaned_data["team_ids"]+ if team_ids:+ args += ["--team-ids", *[str(t) for t in team_ids]]+ if form.cleaned_data["dry_run"]:+ args.append("--dry-run")++ buf = StringIO()+ try:+ call_command("rerun_google_ads_failed_invocations", *args, stdout=buf, stderr=buf)+ except Exception as e:+ buf.write(f"\nCommand raised: {e!r}")+ messages.error(request, "Command raised an exception; see output below.")+ else:+ if form.cleaned_data["dry_run"]:+ messages.info(request, "Dry run complete — no rerun requests were sent.")+ else:+ messages.success(request, "Rerun run complete. Check the output for per-function results.")+ output = buf.getvalue()+ else:+ form = RerunGoogleAdsFailedInvocationsForm()++ return render(+ request,+ "admin/cdp/hogfunction/rerun_google_ads.html",+ {"form": form, "output": output, "title": "Rerun Google Ads failed invocations"},+ )