Skip to content

: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.

fix(stamphog): survive a rate-limited token mint instead of failing the review (#99047)

posthog[bot]775e4fddb446
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index 61e58c06c8be..e96a3fda79b3 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -26,6 +26,7 @@ import random
from collections.abc import Sequence
from dataclasses import dataclass, field
from datetime import UTC, datetime
+from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.parse import urlparse
@@ -132,8 +133,13 @@ STAMPHOG_AI_PRODUCT = "aio_stamphog"
# The cap bounds what a leaked token can spend; the TTL must outlive the 30-minute review activity.
_REVIEWER_TOKEN_CAP_USD = "5"
_REVIEWER_TOKEN_TTL_SECONDS = 3600
-_MINT_ATTEMPTS = 2
+_MINT_ATTEMPTS = 4
_MINT_TIMEOUT_SECONDS = 3
+# Waits of about 1s, 2s and 4s before the retries, plus jitter so a fleet of workers refused at
+# once does not come back in step. A Retry-After the gateway sends wins, clamped to the same
+# ceiling: the whole mint must stay short against the review activity's start-to-close timeout.
+_MINT_BACKOFF_SECONDS = 1.0
+_MINT_MAX_BACKOFF_SECONDS = 10.0
AI_GATEWAY_TOKEN_MINTS = Counter(
"stamphog_ai_gateway_token_mints_total",
@@ -168,14 +174,40 @@ def _connected_user(run: ReviewRun) -> User:
return user
+def _retry_after_seconds(response: requests.Response) -> float | None:
+ """Seconds the gateway asked the caller to wait, from either Retry-After form; None if unusable."""
+ header = response.headers.get("Retry-After")
+ if not header:
+ return None
+ try:
+ return max(0.0, float(header.strip()))
+ except ValueError:
+ pass
+ try:
+ retry_at = parsedate_to_datetime(header)
+ except (TypeError, ValueError):
+ return None
+ if retry_at.tzinfo is None:
+ retry_at = retry_at.replace(tzinfo=UTC)
+ return max(0.0, (retry_at - datetime.now(UTC)).total_seconds())
+
+
+def _mint_backoff_seconds(attempt: int, retry_after: float | None) -> float:
+ """What to wait before the next mint attempt: the gateway's own answer, else exponential backoff."""
+ if retry_after is not None:
+ return min(retry_after, _MINT_MAX_BACKOFF_SECONDS)
+ delay = min(_MINT_BACKOFF_SECONDS * 2**attempt, _MINT_MAX_BACKOFF_SECONDS)
+ return delay + random.uniform(0, delay / 4)
+
+
def _mint_reviewer_scoped_token(gateway: AIGatewayConfig, run: ReviewRun, user: User) -> str:
"""Per-run ``phe_`` minted with the worker's ``phs_``, which never enters the sandbox.
- Pinned to product and team and capped in spend and lifetime, so a leak buys little. Retries once
- on 429, 5xx and network errors; any other refusal is final, and hosted runs have no shared-key
- fallback. A token minted without a requested model pin is revoked and fails the run. Kept
- separate from the tasks and wizard minters: each product owns its failure posture, and this cap
- and TTL are documented invariants rather than ops knobs.
+ Pinned to product and team and capped in spend and lifetime, so a leak buys little. Retries with
+ growing backoff on 429, 5xx and network errors; any other refusal is final, and hosted runs have
+ no shared-key fallback. A token minted without a requested model pin is revoked and fails the
+ run. Kept separate from the tasks and wizard minters: each product owns its failure posture, and
+ this cap and TTL are documented invariants rather than ops knobs.
"""
body: dict[str, object] = {
"cap_usd": _REVIEWER_TOKEN_CAP_USD,
@@ -192,6 +224,7 @@ def _mint_reviewer_scoped_token(gateway: AIGatewayConfig, run: ReviewRun, user:
mint_url = f"{_gateway_root(gateway)}/v1/tokens"
last_error = ""
for attempt in range(_MINT_ATTEMPTS):
+ retry_after: float | None = None
try:
response = requests.post(
mint_url,
@@ -223,11 +256,12 @@ def _mint_reviewer_scoped_token(gateway: AIGatewayConfig, run: ReviewRun, user:
break
if response.status_code == 429 or response.status_code >= 500:
last_error = f"HTTP {response.status_code}"
+ retry_after = _retry_after_seconds(response)
else:
last_error = f"HTTP {response.status_code}: {response.text[:200]}"
break
if attempt < _MINT_ATTEMPTS - 1:
- time.sleep(0.5 + random.uniform(0, 0.25))
+ time.sleep(_mint_backoff_seconds(attempt, retry_after))
AI_GATEWAY_TOKEN_MINTS.labels(result="error").inc()
raise RuntimeError(
f"Could not mint the sandbox gateway token ({last_error}); hosted reviews require the LLM gateway"
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index 5f605f3cac1e..6a77dce914e9 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -98,9 +98,13 @@ class SandboxPhaseError(Exception):
"""
-# One attempt. The activity setup costs nothing and is safe to repeat, and the activity marks its
-# paid phase and records a claim. A higher count belongs in a later change, after this one is on
-# every worker: workflow and activity tasks share one unversioned queue, so a rolling deploy lets a
-# new workflow worker schedule against an old activity worker that writes no claim. A paid-phase
-# failure would then bill a second review.
-SANDBOX_RETRY_POLICY = RetryPolicy(maximum_attempts=1)
+# Two attempts. The free phase — context load, token mint, sandbox config — costs nothing and is
+# safe to repeat, so a refusal there must not burn the whole review. The paid phase is fenced twice:
+# it raises SandboxPhaseError, which this policy excludes, and it records a claim that stops a
+# second sandbox when Temporal retries a lost worker instead. Both fences are on every worker, so
+# the rolling-deploy hole that held this at one attempt is closed.
+SANDBOX_RETRY_POLICY = RetryPolicy(
+ maximum_attempts=2,
+ initial_interval=timedelta(seconds=10),
+ non_retryable_error_types=["SandboxPhaseError"],
+)
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 32b28fe5bb8a..fac6df90154c 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -47,6 +47,7 @@ from products.stamphog.backend.temporal.activities import (
run_review_in_sandbox,
)
from products.stamphog.backend.temporal.constants import (
+ SANDBOX_RETRY_POLICY,
STAMPHOG_SANDBOX_CONTEXT_PATH,
STAMPHOG_SANDBOX_REPO_DIR,
SandboxPhaseError,
@@ -253,6 +254,9 @@ def test_failure_once_the_sandbox_exists_is_not_retried(team, stamphog_chain: St
# stamphog:read can read run.error, and this phase reads an untrusted PR head.
assert run.error == "SandboxPhaseError: the sandbox phase failed with RuntimeError"
assert "modal refused the box" not in (run.error or "")
+ # The marker only saves a run from a second bill while the policy excludes it and retries the rest.
+ assert SANDBOX_RETRY_POLICY.maximum_attempts > 1
+ assert SandboxPhaseError.__name__ in (SANDBOX_RETRY_POLICY.non_retryable_error_types or [])
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
@@ -551,11 +555,14 @@ def test_hosted_review_fails_closed_without_gateway_instead_of_anthropic_fallbac
_GO_GATEWAY_SETTINGS = {"AI_GATEWAY_URL": "https://ai-gateway.test/v1", "AI_GATEWAY_API_KEY": "phs_stamphog_mint"}
-def _mint_response(status_code: int, payload: dict | None = None, text: str = "") -> MagicMock:
+def _mint_response(
+ status_code: int, payload: dict | None = None, text: str = "", headers: dict | None = None
+) -> MagicMock:
response = MagicMock()
response.status_code = status_code
response.json.return_value = payload if payload is not None else {}
response.text = text
+ response.headers = headers or {}
return response
@@ -625,7 +632,8 @@ def test_sandbox_gets_a_scoped_gateway_token_when_the_go_gateway_is_configured(
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_hosted_review_fails_closed_when_the_scoped_token_mint_fails(team, stamphog_chain: StamphogChain) -> None:
- # A mint outage retries once and then fails the run: no sandbox, never a shared-key fallback.
+ # A mint outage is retried with backoff and then fails the run: no sandbox, never a shared-key
+ # fallback.
# Nothing was paid for, so the failure stays retryable (not SandboxPhaseError).
_repo_config(team.id)
event = _register_review(stamphog_chain, 114, "sha114a")
@@ -642,11 +650,42 @@ def test_hosted_review_fails_closed_when_the_scoped_token_mint_fails(team, stamp
assert run.status == ReviewRunStatus.FAILED
assert "gateway" in (run.error or "").lower()
assert "HTTP 503" in (run.error or "")
- assert mint.call_count == 2
+ assert mint.call_count == activities._MINT_ATTEMPTS
assert not stamphog_chain.sandbox_class.created_configs
assert not (run.error or "").startswith("SandboxPhaseError")
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_scoped_token_mint_waits_out_a_rate_limit_and_obeys_retry_after(team, stamphog_chain: StamphogChain) -> None:
+ # A rate-limited mint must not cost the review. The mint costs nothing, so it waits as long as the
+ # gateway asked and then keeps trying, and only a burst longer than every attempt fails the run.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 123, "sha123a")
+ mint = MagicMock(
+ side_effect=[
+ _mint_response(429, text="slow down", headers={"Retry-After": "7"}),
+ _mint_response(429, text="slow down"),
+ _mint_response(201, {"token": "phe_run"}),
+ _mint_response(200, {"revoked": True}),
+ ]
+ )
+ sleeps: list[float] = []
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS),
+ patch.object(activities.requests, "post", mint),
+ patch.object(activities.time, "sleep", side_effect=sleeps.append),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.COMPLETED
+ assert stamphog_chain.sandbox_class.created_configs[0].environment_variables["AI_GATEWAY_API_KEY"] == "phe_run"
+ # The header wins the first wait; the second grows on its own, jittered but bounded.
+ assert sleeps[0] == 7.0
+ assert 2.0 <= sleeps[1] <= 2.5
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_scoped_token_mint_does_not_retry_a_credential_rejection(team, stamphog_chain: StamphogChain) -> None:
# A 4xx other than 429 is a final answer about the worker's own credential; retrying it only