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.

chore(stamphog): dedicated anthropic key, keep label on backend failure (#60813)

Paul D'Ambra0305eb3cc389
diff --git a/.github/workflows/pr-approval-agent.yml b/.github/workflows/pr-approval-agent.yml
index 4908e0d5d5db..ede57a1dd582 100644
--- a/.github/workflows/pr-approval-agent.yml
+++ b/.github/workflows/pr-approval-agent.yml
@@ -61,7 +61,10 @@ jobs:
- name: Run review
env:
- ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
+ # Dedicated key so a rotation of the shared ANTHROPIC_API_KEY
+ # doesn't break stamphog (and vice versa). The env var name
+ # stays ANTHROPIC_API_KEY — that's what the Claude Agent SDK reads.
+ ANTHROPIC_API_KEY: ${{ secrets.STAMPHOG_ANTHROPIC_API_KEY }}
POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_TOKEN }}
GH_TOKEN: ${{ steps.app-token.outputs.token }}
run: |
@@ -111,10 +114,14 @@ jobs:
--repo "$REPO"
fi
- # Non-APPROVED verdict removes the label, breaking the
- # auto-rerun loop until a human re-applies it after
- # addressing the feedback.
- if [ "$VERDICT" != "APPROVED" ]; then
+ # A substantive non-APPROVED verdict (REFUSE/ESCALATE)
+ # removes the label, breaking the auto-rerun loop until a
+ # human re-applies it after addressing the feedback. ERROR
+ # means the review agent couldn't reach its LLM backend
+ # (auth/credit/outage) — that's not a verdict on the PR, so
+ # keep the label and let it retry rather than silently
+ # dropping it across every queued PR during an outage.
+ if [ "$VERDICT" != "APPROVED" ] && [ "$VERDICT" != "ERROR" ]; then
gh pr edit "$PR" --remove-label stamphog \
--repo "$REPO"
fi
diff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.md
index bad01af942e7..5b7ee817e6bb 100644
--- a/tools/pr-approval-agent/README.md
+++ b/tools/pr-approval-agent/README.md
@@ -8,7 +8,15 @@ Deterministic safety gates first, then Claude reviews for showstoppers.
Add the `stamphog` label to a non-draft PR.
The GitHub Action runs the agent and posts an approval or comment.
On approval the label stays so it's visible which PRs were stamphog'd.
-On failure the label is removed so it can be re-applied.
+On a substantive non-approval (`REFUSE`/`ESCALATE`) the label is removed so it
+can be re-applied once the feedback is addressed.
+If the review agent can't reach its LLM backend (credentials, credit, or
+outage) it returns `ERROR` and **keeps** the label — a transient infra failure
+must not silently drop labels across every queued PR. The review retries on the
+next push, or re-apply the label once the backend recovers. When the whole
+fleet of stamphog reviews suddenly returns `ERROR`, suspect the
+`STAMPHOG_ANTHROPIC_API_KEY` org secret first (stamphog uses its own dedicated
+Anthropic key, separate from the shared `ANTHROPIC_API_KEY`).
### Local testing
diff --git a/tools/pr-approval-agent/dismiss_check.py b/tools/pr-approval-agent/dismiss_check.py
index 816a287c9438..451fa2515898 100644
--- a/tools/pr-approval-agent/dismiss_check.py
+++ b/tools/pr-approval-agent/dismiss_check.py
@@ -13,9 +13,9 @@ the environment and prints a single-line `Decision` JSON on stdout:
The two booleans are orthogonal so each downstream workflow job gates on
exactly the question it owns: the `dismiss` job reads `dismiss_approval`,
the `review` job reads `run_review`. Decisions are constructed only via
-`Decision.retain`, `Decision.dismiss_and_review`, `Decision.no_op`, and
-`Decision.error` — together they cover every legitimate combination, and
-the impossible "dismiss the approval but skip re-review" case is
+`Decision.retain`, `Decision.review_only`, `Decision.dismiss_and_review`,
+and `Decision.error` — together they cover every legitimate combination,
+and the impossible "dismiss the approval but skip re-review" case is
unrepresentable.
Anything ambiguous (force-push, mixed paths, fetch error, foreign-branch
@@ -84,12 +84,13 @@ class Decision:
return cls(dismiss_approval=True, run_review=True, reason=str(reason))
@classmethod
- def no_op(cls, reason: Reason) -> "Decision":
- """No prior approval to act on — nothing to do; the original `labeled`
- event already fired a review, and the label-strip on non-APPROVED is
- the canonical kill-switch. If a human dismissed the bot approval and
- kept the label, they can re-label to request a fresh review."""
- return cls(dismiss_approval=False, run_review=False, reason=reason)
+ def review_only(cls, reason: Reason) -> "Decision":
+ """No prior bot approval to dismiss, but the label is still on and the
+ agent hasn't approved yet — re-run the review on this push. Covers the
+ first-run ERROR case (LLM backend was down, so the label was retained
+ without an approval): the push actually retries the review instead of
+ leaving the PR labeled but stuck until someone re-applies the label."""
+ return cls(dismiss_approval=False, run_review=True, reason=reason)
@classmethod
def error(cls, exc: Exception) -> "Decision":
@@ -201,7 +202,7 @@ def evaluate_delta(last_approved_sha: str, head_sha: str, cwd: Path, base_ref: s
def decide(repo: str, pr_number: int, head_sha: str, cwd: Path, base_ref: str = "origin/master") -> Decision:
last_approved_sha = find_last_approved_sha(repo, pr_number)
if last_approved_sha is None:
- return Decision.no_op(Reason.NO_PRIOR_APPROVAL)
+ return Decision.review_only(Reason.NO_PRIOR_APPROVAL)
return replace(
evaluate_delta(last_approved_sha, head_sha, cwd, base_ref),
last_approved_sha=last_approved_sha,
diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.py
index 08698d270d78..c250c879486e 100644
--- a/tools/pr-approval-agent/review_pr.py
+++ b/tools/pr-approval-agent/review_pr.py
@@ -352,6 +352,7 @@ class Pipeline:
print(_dim(" Calling reviewer..."))
max_retries = 3
+ reviewer_unavailable = False
for attempt in range(max_retries):
try:
self.reviewer_output = reviewer.review(
@@ -368,9 +369,22 @@ class Pipeline:
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": "ESCALATE",
- "reasoning": f"Review agent failed after {max_retries} attempts — needs human review.",
+ "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)],
}
@@ -383,10 +397,17 @@ class Pipeline:
for issue in issues:
print(_warn(f" {issue}"))
- # Gates are authoritative — LLM can tighten but never loosen
+ # Gates are authoritative — LLM can tighten but never loosen. A real
+ # gate denial outranks an unavailable reviewer: still REFUSE (and let
+ # the label strip), because the deny is deterministic and actionable.
if gate_verdict == "DENIED":
self.final_verdict = "REFUSED"
print(f"\n{_fail('REFUSED')} — gates denied")
+ elif reviewer_unavailable:
+ # Distinct from a substantive REFUSE/ESCALATE: the workflow keeps
+ # the label so a transient outage doesn't drop it across every PR.
+ self.final_verdict = "ERROR"
+ print(f"\n{_warn('ERROR')} — review agent unavailable; label retained for retry")
elif gate_verdict == "AUTO-APPROVED" and llm_verdict in ("REFUSE", "ESCALATE"):
self.final_verdict = "ESCALATE"
print(f"\n{_warn('ESCALATE')} — gates auto-approved but LLM disagrees")
diff --git a/tools/pr-approval-agent/test_dismiss_check.py b/tools/pr-approval-agent/test_dismiss_check.py
index 855d8cad4e85..0b5010e76fd0 100644
--- a/tools/pr-approval-agent/test_dismiss_check.py
+++ b/tools/pr-approval-agent/test_dismiss_check.py
@@ -362,12 +362,13 @@ def test_merge_from_non_base_branch_dismisses(repo: Path) -> None:
def test_decide_no_prior_approval(monkeypatch: pytest.MonkeyPatch, repo: Path) -> None:
- # No prior bot approval → no_op. Re-review here would burn LLM credits
- # for a state we didn't create (a human dismissed the approval out-of-
- # band) and the label-add path is the canonical re-review trigger.
+ # No prior bot approval, but the label is still on (decide-delta only runs
+ # when it is) and the agent hasn't approved — re-run the review on this
+ # push so the first-run ERROR case (LLM backend down, label retained)
+ # actually retries instead of staying labeled but stuck.
monkeypatch.setattr(dismiss_check, "find_last_approved_sha", lambda *_: None)
result = decide("PostHog/posthog", 1, _head(repo), repo)
- _assert_decision(result, dismiss=False, review=False, reason="no_prior_approval")
+ _assert_decision(result, dismiss=False, review=True, reason="no_prior_approval")
assert result.last_approved_sha is None
diff --git a/tools/pr-approval-agent/test_review_pr.py b/tools/pr-approval-agent/test_review_pr.py
index fcb612956635..e58da758fbf1 100644
--- a/tools/pr-approval-agent/test_review_pr.py
+++ b/tools/pr-approval-agent/test_review_pr.py
@@ -2,6 +2,7 @@
import sys
+import pytest
from unittest.mock import MagicMock
# review_pr.py is a uv-script; its `claude_agent_sdk` dep is installed by
@@ -9,8 +10,9 @@ from unittest.mock import MagicMock
sys.modules.setdefault("claude_agent_sdk", MagicMock())
sys.modules.setdefault("claude_agent_sdk.types", MagicMock())
+import review_pr # noqa: E402
from github import PRData # noqa: E402
-from review_pr import Pipeline # noqa: E402
+from review_pr import GateResult, Pipeline # noqa: E402
def _fake_pr(head_sha: str) -> PRData:
@@ -46,3 +48,43 @@ def test_to_dict_includes_head_sha() -> None:
output = pipeline.to_dict()
assert output["head_sha"] == "07dfeff14d95be1247e4c8c1065fd958a367389e"
+
+
+class _RaisingReviewer:
+ """Stand-in for Reviewer whose LLM call always fails (backend down)."""
+
+ 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: success")
+
+
+ "gate_verdict, expected_final",
+ [
+ ("PENDING", "ERROR"),
+ ("AUTO-APPROVED", "ERROR"),
+ ("DENIED", "REFUSED"),
+ ],
+)
+def test_backend_failure_yields_error_except_when_gates_deny(
+ monkeypatch: pytest.MonkeyPatch, gate_verdict: str, expected_final: str
+) -> None:
+ """A failed LLM call must surface as ERROR (label retained) unless gates
+ already DENIED — a deterministic denial outranks an unavailable reviewer."""
+ monkeypatch.setattr(review_pr, "Reviewer", _RaisingReviewer)
+ 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)
+
+ assert pipeline.final_verdict == expected_final
+ if expected_final == "ERROR":
+ assert pipeline.reviewer_output is not None
+ assert pipeline.reviewer_output["verdict"] == "ERROR"