: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): distinguish retryable vs non-retryable errors and bump quick turn limit (#61612)
mendral-app[bot]3777b2cef3d2
diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.pyindex c250c879486e..78b442ef3019 100644--- a/tools/pr-approval-agent/review_pr.py+++ b/tools/pr-approval-agent/review_pr.py@@ -95,6 +95,22 @@ def _dim(msg: str) -> str:return f"\033[2m{msg}\033[0m"+# ── Error classification ─────────────────────────────────────────++# Patterns that indicate non-retryable failures (agent limitations, not infra).+_NON_RETRYABLE_PATTERNS = (+ "Reached maximum number of turns",+ "could not produce valid structured output",+)+++def _is_retryable_error(err_msg: str) -> bool:+ """Return True if the error looks like an infrastructure/transient issue+ that is worth retrying (API timeouts, rate limits, overload).+ Return False for non-retryable errors like turn-limit exhaustion."""+ return not any(pattern in err_msg for pattern in _NON_RETRYABLE_PATTERNS)++# ── Gate result ──────────────────────────────────────────────────@@ -362,32 +378,49 @@ class Pipeline:)breakexcept Exception as e:- if attempt < max_retries - 1:+ err_str = str(e)+ is_retryable = _is_retryable_error(err_str)++ if is_retryable and attempt < max_retries - 1:wait = 2 ** (attempt + 1)print(_warn(f"Reviewer failed (attempt {attempt + 1}/{max_retries}): {e}"))print(_dim(f" Retrying in {wait}s..."))time.sleep(wait)else:- print(_fail(f"Reviewer failed after {max_retries} attempts: {e}"))- print(- _warn(- " This is an LLM backend failure (credentials, credit, or outage), "- "not a verdict on the PR. Check the STAMPHOG_ANTHROPIC_API_KEY "- "secret (or local ANTHROPIC_API_KEY)."- )- )reviewer_unavailable = True- self.reviewer_output = {- "verdict": "ERROR",- "reasoning": (- "The review agent couldn't reach its LLM backend — an infrastructure "- "or credentials issue, not a problem with this PR. The `stamphog` label "- "has been kept; the review retries automatically on the next push, or "- "re-apply the label once the backend recovers."- ),- "risk": "unknown",- "issues": [str(e)],- }+ if is_retryable:+ print(_fail(f"Reviewer failed after {max_retries} attempts: {e}"))+ print(+ _warn(+ " This is an LLM backend failure (credentials, credit, or outage), "+ "not a verdict on the PR. Check the STAMPHOG_ANTHROPIC_API_KEY "+ "secret (or local ANTHROPIC_API_KEY)."+ )+ )+ self.reviewer_output = {+ "verdict": "ERROR",+ "reasoning": (+ "The review agent couldn't reach its LLM backend — an infrastructure "+ "or credentials issue, not a problem with this PR. The `stamphog` label "+ "has been kept; the review retries automatically on the next push, or "+ "re-apply the label once the backend recovers."+ ),+ "risk": "unknown",+ "issues": [err_str],+ }+ else:+ print(_fail(f"Reviewer hit a non-retryable error: {e}"))+ self.reviewer_output = {+ "verdict": "ERROR",+ "reasoning": (+ "The review agent could not complete its analysis for this PR "+ "(likely too complex for the allocated turn budget). "+ "The `stamphog` label has been kept; a human review is needed."+ ),+ "risk": "unknown",+ "issues": [err_str],+ }+ breakllm_verdict = self.reviewer_output.get("verdict", "UNKNOWN")print(f" Verdict: {llm_verdict}")diff --git a/tools/pr-approval-agent/reviewer.py b/tools/pr-approval-agent/reviewer.pyindex 140a64821ee0..88f564af00ea 100644--- a/tools/pr-approval-agent/reviewer.py+++ b/tools/pr-approval-agent/reviewer.py@@ -225,7 +225,7 @@ class Reviewer:allowed_tools=["Read", "Grep", "Glob"],disallowed_tools=["Write", "Edit", "NotebookEdit", "Bash", "Agent", "WebFetch", "WebSearch"],cwd=str(self.repo_root),- max_turns=3 if quick else 20,+ max_turns=5 if quick else 20,model=MODEL,permission_mode="dontAsk",output_format=VERDICT_SCHEMA,diff --git a/tools/pr-approval-agent/test_review_pr.py b/tools/pr-approval-agent/test_review_pr.pyindex e58da758fbf1..5374b6de296f 100644--- a/tools/pr-approval-agent/test_review_pr.py+++ b/tools/pr-approval-agent/test_review_pr.py@@ -60,6 +60,16 @@ class _RaisingReviewer:raise RuntimeError("Claude Code returned an error result: success")+class _TurnLimitReviewer:+ """Stand-in for Reviewer that hits the max turns limit."""++ def __init__(self, *args: object, **kwargs: object) -> None:+ pass++ def review(self, *args: object, **kwargs: object) -> dict:+ raise RuntimeError("Claude Code returned an error result: Reached maximum number of turns (5)")++@pytest.mark.parametrize("gate_verdict, expected_final",[@@ -88,3 +98,48 @@ def test_backend_failure_yields_error_except_when_gates_deny(if expected_final == "ERROR":assert pipeline.reviewer_output is not Noneassert pipeline.reviewer_output["verdict"] == "ERROR"+ # Retryable errors should mention infrastructure+ assert "infrastructure" in pipeline.reviewer_output["reasoning"]+++ "gate_verdict, expected_final",+ [+ ("PENDING", "ERROR"),+ ("AUTO-APPROVED", "ERROR"),+ ("DENIED", "REFUSED"),+ ],+)+def test_turn_limit_error_not_retried(monkeypatch: pytest.MonkeyPatch, gate_verdict: str, expected_final: str) -> None:+ """A turn-limit error is non-retryable and should give a clear message+ about complexity rather than blaming infrastructure. When gates DENIED,+ the deterministic denial still outranks the error."""+ call_count = 0+ original_review = _TurnLimitReviewer.review++ def counting_review(self, *args, **kwargs):+ nonlocal call_count+ call_count += 1+ return original_review(self, *args, **kwargs)++ monkeypatch.setattr(review_pr, "Reviewer", _TurnLimitReviewer)+ monkeypatch.setattr(_TurnLimitReviewer, "review", counting_review)+ monkeypatch.setattr(review_pr.time, "sleep", lambda _s: None)+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)++ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ pipeline.pr = _fake_pr(head_sha="abc123")+ pipeline.classification = {"tier": "T1-agent", "breadth": "narrow"}+ pipeline.gate_results = [GateResult("deny-list", gate_verdict != "DENIED", "")]++ pipeline._llm_review(gate_verdict)++ # Non-retryable: should only be called once, not retried+ assert call_count == 1+ assert pipeline.final_verdict == expected_final+ if expected_final == "ERROR":+ assert pipeline.reviewer_output is not None+ assert "could not complete its analysis" in pipeline.reviewer_output["reasoning"]+ # Should NOT mention infrastructure/credentials+ assert "infrastructure" not in pipeline.reviewer_output["reasoning"]+ assert "credentials" not in pipeline.reviewer_output["reasoning"]