: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(stamphog): tell the author when a relabel lands in the cooldown (#118155)
Marcus Hofb0344ba72dac
diff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex 07fdfa92ab55..a939c84cdacd 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -30,9 +30,11 @@ Every other verdict is posted once per run as a comment review on the same surfaA run that produced no verdict posts a short failure notice the same way, unless a newer run already holds the same head.The engine reports `APPROVED` and `REFUSED`, and the API exposes them lowercase as `approved` and `refused`.-The trigger label only exists in label-triggered mode, and only a substantive non-approval removes it.+The trigger label only exists in label-triggered mode, and of the verdicts only a substantive non-approval removes it.So the label can be re-applied once the feedback is addressed.A verdict that says nothing about the PR keeps the label, and the next push retries.+A label can request at most one review per PR every 10 minutes.+A label added inside that window starts nothing, so stamphog removes it again and says in its status comment when a relabel will work.`WAIT` means a reviewer bot still had a review in flight, or the `Migration risk` check had not reported yet.`ERROR` means the run failed before it could judge the PR, because the LLM backend was unreachable or the reviewer hit a non-retryable analysis failure such as its turn limit.A transient failure must not silently drop labels across every queued PR.diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.pyindex 1c92b4055b87..5f45433d6e56 100644--- a/products/stamphog/backend/tasks/tasks.py+++ b/products/stamphog/backend/tasks/tasks.py@@ -7,8 +7,10 @@ a fresh ReviewRun, and kicks off the Temporal review workflow once the row commi"""import re+import mathfrom collections.abc import Collectionfrom dataclasses import dataclass+from datetime import UTC, datetimefrom typing import Any, castfrom django.core.cache import cache@@ -50,6 +52,7 @@ from products.stamphog.backend.logic.audiences import ResolvedAudience, resolve_from products.stamphog.backend.logic.github_client import StamphogGitHubClientfrom products.stamphog.backend.logic.installations import delete_installation, remove_from_installation_snapshotfrom products.stamphog.backend.logic.review_trigger import derive_review_trigger+from products.stamphog.backend.logic.scrubbing import neutralize_active_markdown, scrub_credentialsfrom products.stamphog.backend.models import (PullRequest,PullRequestAudience,@@ -105,7 +108,8 @@ _INBOX_OPT_OUT_DISMISS_MESSAGE = ()# Per-PR cooldown for label-triggered re-reviews, so removing/re-adding the trigger label can't spam-# sandbox + LLM runs. Set only when a `labeled` event actually queues a run in LABEL mode.+# sandbox + LLM runs. Set only when a `labeled` event actually queues a run in LABEL mode. The value is+# the epoch second the cooldown ends, so a rejected relabel can tell the author when to try again.STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS = 10 * 60STAMPHOG_LABEL_REREVIEW_KEY_PREFIX = "stamphog:label_rereview:"@@ -688,6 +692,76 @@ def _clear_trigger_label_from_bot_pr(installation_id: str, repo: str, pr: dict[slogger.warning("stamphog_pr_event_bot_label_cleanup_failed", repo=repo, pr_number=pr_number, exc_info=True)+def _label_cooldown_message(trigger_label: str, cooldown_ends_at: Any) -> str:+ # A key armed before the expiry was stored holds True, which says nothing about when it ends.+ if isinstance(cooldown_ends_at, bool) or not isinstance(cooldown_ends_at, int | float):+ when = f"in up to {STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS // 60} minutes"+ else:+ # Rounded up so relabeling at the stated minute never lands inside the cooldown.+ ends_at_seconds = math.ceil(cooldown_ends_at / 60) * 60+ ends_at = datetime.fromtimestamp(ends_at_seconds, tz=UTC)+ minutes_left = max(1, math.ceil((ends_at_seconds - timezone.now().timestamp()) / 60))+ when = f"at {ends_at:%H:%M} UTC (in about {minutes_left} minute{'s' if minutes_left != 1 else ''})"+ return (+ f"**No review started.** stamphog started a review of this pull request less than "+ f"{STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS // 60} minutes ago, and a label can request at most one "+ f"review per {STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS // 60} minutes. "+ f"The `{trigger_label}` label has been removed. Add it again {when} to request a fresh review."+ )+++def _reject_label_in_cooldown(repo_config: StamphogRepoConfig, pr: dict[str, Any], delivery_id: str) -> None:+ """Take the trigger label back off a PR that was relabeled inside the cooldown, and say why.++ Left alone, the label would sit on the PR as if a review had been requested while nothing runs.+ The status comment is edited in place, so toggling the label repeatedly can't stack comments.++ This is best effort, like the bot-author cleanup: a GitHub failure is logged and not retried.+ """+ pr_number = pr["number"]+ try:+ # A delayed delivery of the label add that armed the cooldown must not remove a newer label.+ incoming_updated_at = parse_datetime(pr.get("updated_at") or "")+ stored_updated_at = (+ PullRequest.objects.for_team(repo_config.team_id)+ .using(router.db_for_write(PullRequest))+ .filter(repo_config=repo_config, pr_number=pr_number)+ .values_list("payload_updated_at", flat=True)+ .first()+ )+ if incoming_updated_at and stored_updated_at and incoming_updated_at < stored_updated_at:+ return+ # A late redelivery of the add that armed the cooldown can outlive the delivery dedup.+ if (+ delivery_id+ and ReviewRun.objects.for_team(repo_config.team_id)+ .using(router.db_for_write(ReviewRun))+ .filter(delivery_id=delivery_id)+ .exists()+ ):+ return+ cooldown_ends_at = cache.get(_label_cooldown_key(repo_config, pr_number))+ client = StamphogGitHubClient(repo_config.installation_id)+ client.remove_pr_label(repo_config.repository, pr_number, repo_config.trigger_label)+ # upsert_sticky_comment reads then creates, so overlapping deliveries could each post a comment.+ if not cache.add(f"{_label_cooldown_key(repo_config, pr_number)}:notice", True, timeout=60):+ return+ client.upsert_sticky_comment(+ repo_config.repository,+ pr_number,+ neutralize_active_markdown(+ scrub_credentials(_label_cooldown_message(repo_config.trigger_label, cooldown_ends_at))+ ),+ )+ except Exception:+ logger.warning(+ "stamphog_pr_event_label_cooldown_notice_failed",+ repo=repo_config.repository,+ pr_number=pr_number,+ exc_info=True,+ )++def _retract_stale_approvals_on_skip(repo_config: StamphogRepoConfig, pr: dict[str, Any], message: str) -> None:"""Retract a standing stamphog approval when a head-changing event is skipped before the workflow.@@ -1186,6 +1260,8 @@ def process_pull_request_event(payload: dict[str, Any], delivery_id: str) -> Nonexcept Exception as e:logger.exception("stamphog_pr_event_label_skip_dismiss_failed", delivery_id=delivery_id, error=str(e))raise cast(Any, process_pull_request_event).retry(exc=e)+ if mode_skip_reason == "label_cooldown":+ _reject_label_in_cooldown(repo_config, pr, delivery_id)logger.info("stamphog_pr_event_skipped", repo=repo, pr_number=pr_number, reason=mode_skip_reason)if delivery_id:_mark_pr_event_processed(delivery_id)@@ -1357,7 +1433,11 @@ def process_pull_request_event(payload: dict[str, Any], delivery_id: str) -> Non# Arm the cooldown only once a label-triggered run actually queued, so a skipped or failed# attempt doesn't block the next legitimate label add.if action == "labeled" and repo_config.review_mode == ReviewMode.LABEL:- cache.set(_label_cooldown_key(repo_config, pr_number), True, timeout=STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS)+ cache.set(+ _label_cooldown_key(repo_config, pr_number),+ timezone.now().timestamp() + STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS,+ timeout=STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS,+ )logger.info("stamphog_pr_event_queued",diff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.pyindex 0dfa43bff1f3..e53b74ffde32 100644--- a/products/stamphog/backend/tests/test_tasks.py+++ b/products/stamphog/backend/tests/test_tasks.py@@ -3,6 +3,7 @@ import contextlibfrom typing import Anyimport pytest+import time_machinefrom unittest.mock import patchfrom django.core.cache import cache@@ -28,6 +29,7 @@ from products.stamphog.backend.models import ()from products.stamphog.backend.tasks.tasks import (_INBOX_OPT_OUT_DISMISS_MESSAGE,+ STAMPHOG_PR_EVENT_IDEMPOTENCY_KEY_PREFIX,_parse_pr_url,_upsert_pull_request,process_inbox_pr_review,@@ -390,21 +392,48 @@ def test_review_mode_gates_events(team, repo_config, review_mode, payload_kwargsmock_execute.assert_not_called()+ "retrigger_updated_at,redeliver,expect_label_removed",+ [+ ("2026-10-15T14:03:30Z", False, True),+ ("2026-10-15T14:00:20Z", False, True),+ ("2026-10-15T14:00:10Z", False, False),+ ("2026-10-15T14:00:20Z", True, False),+ ],+ ids=["fresh_relabel", "same_second_relabel", "stale_delivery", "late_redelivery"],+)@pytest.mark.django_db(databases=PRODUCT_DATABASES)-def test_labeled_rereview_cooldown_skips_rapid_retrigger(team, repo_config):+def test_labeled_rereview_cooldown_skips_rapid_retrigger(+ team, repo_config, retrigger_updated_at: str, redeliver: bool, expect_label_removed: bool+):# Removing and re-adding the trigger label within the cooldown must not queue a second sandbox +# LLM run — the cheap re-review spam the cooldown exists for.with team_scope(team.id):repo_config.review_mode = ReviewMode.LABELrepo_config.save()- payload = _pr_payload(action="labeled", labels=["stamphog"], added_label="stamphog")- _run_task(payload, "delivery-label-1", team.id)- mock_execute = _run_task(payload, "delivery-label-2", team.id)+ def labeled(updated_at: str) -> dict:+ return _pr_payload(action="labeled", labels=["stamphog"], added_label="stamphog", updated_at=updated_at)++ first_delivery = f"delivery-label-1-{uuid.uuid4()}"+ with time_machine.travel("2026-10-15T14:00:20Z", tick=False):+ first = _run_task(labeled("2026-10-15T14:00:20Z"), first_delivery, team.id)+ retrigger_delivery = first_delivery if redeliver else f"delivery-label-2-{uuid.uuid4()}"+ cache.delete(f"{STAMPHOG_PR_EVENT_IDEMPOTENCY_KEY_PREFIX}{retrigger_delivery}")+ with time_machine.travel("2026-10-15T14:03:30Z", tick=False):+ mock_execute = _run_task(labeled(retrigger_updated_at), retrigger_delivery, team.id)with team_scope(team.id):assert ReviewRun.objects.count() == 1mock_execute.assert_not_called()+ first.github.remove_pr_label.assert_not_called()+ if not expect_label_removed:+ mock_execute.github.remove_pr_label.assert_not_called()+ mock_execute.github.upsert_sticky_comment.assert_not_called()+ return+ mock_execute.github.remove_pr_label.assert_called_once_with(REPO, 42, "stamphog")+ _, _, body = mock_execute.github.upsert_sticky_comment.call_args.args+ assert "14:11 UTC (in about 8 minutes)" in body@pytest.mark.django_db(databases=PRODUCT_DATABASES)