: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(review-hog): stop retrying review units the gateway rejected (#113895)
Alessandro Pogliaghi72719c886632
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.pyindex 29df31a1d877..2bb367709bab 100644--- a/products/review_hog/backend/reviewer/constants.py+++ b/products/review_hog/backend/reviewer/constants.py@@ -426,6 +426,10 @@ MAX_CONCURRENT_SANDBOXES = 10# (a total wipeout — e.g. the sandbox layer down — must not look like a clean PR).FAN_OUT_FAILURE_FLOOR = 0.70+NON_RETRYABLE_UNIT_FAILURE_CATEGORIES = frozenset(+ {"upstream_request_rejected", "task_spend_limit", "subscription_usage_limit", "content_block_rejection"}+)+# Attempts for a chunk's warm validation session. Retries are cheap — skip-resume re-validates only# issues without a persisted verdict. On the final attempt a failed turn is skipped, not raised.VALIDATION_MAX_ATTEMPTS = 2diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 1d4718973ae7..e2930e4f2cf9 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -42,6 +42,7 @@ from products.review_hog.backend.reviewer.constants import (CHUNKING_RUNTIME_ADAPTER,DEFAULT_URGENCY_THRESHOLD,FLASH_LENSES,+ NON_RETRYABLE_UNIT_FAILURE_CATEGORIES,REVIEW_MODE_FLASH,REVIEW_MODE_FULL,SINGLE_AGENT_CHUNK_ID,@@ -170,6 +171,7 @@ from products.signals.backend.artefact_schemas import CodeReview, CodeReviewCounfrom products.signals.backend.enums import ReportPriorityfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users+from products.tasks.backend.facade.agents import AgentTurnFailedfrom products.tasks.backend.facade.run_config import ReasoningEffortif TYPE_CHECKING:@@ -586,6 +588,11 @@ def _sandbox_workflow_id_prefix(step_name: str) -> str:return f"{activity.info().workflow_id}:{step_name}".lower()+def _raise_if_non_retryable_unit_failure(exc: BaseException) -> None:+ if isinstance(exc, AgentTurnFailed) and exc.category in NON_RETRYABLE_UNIT_FAILURE_CATEGORIES:+ raise ApplicationError(str(exc), non_retryable=True, type=exc.category) from exc++async def _refresh_status_comment(team_id: int, report_id: str, review_mode: str, review_design: str = REVIEW_DESIGN_PIPELINE) -> None:@@ -1217,21 +1224,25 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:else f"issues-review-p{input.pass_number}-c{input.chunk_id}")async with ReviewActivityHeartbeater(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha):- review = await run_sandbox_review(- team_id=input.team_id,- user_id=input.user_id,- repository=input.repository,- branch=input.branch,- prompt=prompt,- system_prompt=REVIEW_SYSTEM_PROMPT,- model_to_validate=IssuesReview,- step_name=step_name,- workflow_id_prefix=_sandbox_workflow_id_prefix(step_name),- runtime_adapter=arm.runtime_adapter,- model=arm.model,- reasoning_effort=arm.reasoning_effort,- initial_permission_mode=arm.initial_permission_mode,- )+ try:+ review = await run_sandbox_review(+ team_id=input.team_id,+ user_id=input.user_id,+ repository=input.repository,+ branch=input.branch,+ prompt=prompt,+ system_prompt=REVIEW_SYSTEM_PROMPT,+ model_to_validate=IssuesReview,+ step_name=step_name,+ workflow_id_prefix=_sandbox_workflow_id_prefix(step_name),+ runtime_adapter=arm.runtime_adapter,+ model=arm.model,+ reasoning_effort=arm.reasoning_effort,+ initial_permission_mode=arm.initial_permission_mode,+ )+ except AgentTurnFailed as exc:+ _raise_if_non_retryable_unit_failure(exc)+ raise# Stamp each issue's perspective (the skill that ran) here, not in combine — it survives the# persisted result + resume, and keeps `source_perspective` = skill_name, decoupled from the enum.for issue in review.issues:@@ -1604,9 +1615,10 @@ async def validate_chunk_activity(input: ValidateChunkInput) -> ValidateChunkResmodel_to_validate=IssueValidation,label=issue.id,)- except Exception:+ except Exception as exc:+ _raise_if_non_retryable_unit_failure(exc)if session is None:- # Session never opened (sandbox-level) — raise so Temporal retries the chunk+ # Session never opened (sandbox-level) — raise so Temporal retries a retryable failure# and the failure floor catches a real outage, not just one bad issue.raiseif not final_attempt:diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.pyindex 5e2eff4e34cf..8502e56af1af 100644--- a/products/review_hog/backend/temporal/workflow.py+++ b/products/review_hog/backend/temporal/workflow.py@@ -7,11 +7,12 @@ consumer reloads its inputs from the persisted artefact rows (`pr_snapshot`, finunbounded payload hits Temporal's ~2 MiB cap. Stage progress is logged via `workflow.logger` so itstreams in the worker log (the former stdout banners).-The fan-out children dispatch per-unit sandbox activities (each retried) under a fresh-`asyncio.Semaphore` and `gather(return_exceptions=True)`, so a minority of failed units degrade-best-effort; a near-total wipeout (> `FAN_OUT_FAILURE_FLOOR`) fails the run loudly instead of-finalizing an empty review as success. Publishing is per-run: the final stage posts to GitHub only-when `inputs.publish` is set (the cloud label trigger), and is skipped for eval / CLI runs.+The fan-out children dispatch per-unit sandbox activities (each retried unless the agent reports a+non-retryable failure) under a fresh `asyncio.Semaphore` and `gather(return_exceptions=True)`, so a+minority of failed units degrade best-effort; a near-total wipeout (> `FAN_OUT_FAILURE_FLOOR`) fails+the run loudly instead of finalizing an empty review as success. Publishing is per-run: the final+stage posts to GitHub only when `inputs.publish` is set (the cloud label trigger), and is skipped for+eval / CLI runs."""import json@@ -148,10 +149,19 @@ def _enforce_failure_floor(stage: str, failed: int, total: int) -> None:"""if total and failed / total > FAN_OUT_FAILURE_FLOOR:raise ApplicationError(- f"{stage}: {failed}/{total} units failed (> {FAN_OUT_FAILURE_FLOOR:.0%}); failing the run"+ f"{stage}: {failed}/{total} units failed (> {FAN_OUT_FAILURE_FLOOR:.0%}); failing the run",+ non_retryable=True,)+def _non_retryable_cause(exc: BaseException | None) -> ApplicationError | None:+ while exc is not None:+ if isinstance(exc, ApplicationError) and exc.non_retryable:+ return exc+ exc = exc.__cause__+ return None++@dataclassclass ReviewPerspectivesInputs(SandboxStageInput):chunk_ids: list[int]@@ -397,15 +407,25 @@ class ReviewPRWorkflow:@temporalio.workflow.runasync def run(self, inputs: ReviewPRWorkflowInputs) -> str:completed = False+ non_retryable = Falsetry:result = await self._run(inputs)completed = Truereturn result+ except Exception as e:+ cause = _non_retryable_cause(e)+ if cause is None:+ raise+ non_retryable = True+ raise ApplicationError(str(e), non_retryable=True, type=cause.type) from efinally:info = workflow.info()retry = info.retry_policyterminal = (- completed or retry is None or (retry.maximum_attempts > 0 and info.attempt >= retry.maximum_attempts)+ completed+ or non_retryable+ or retry is None+ or (retry.maximum_attempts > 0 and info.attempt >= retry.maximum_attempts))if (workflow.patched("remove-reviewhog-trigger-label-2026-08")diff --git a/products/review_hog/backend/tests/test_review_activity.py b/products/review_hog/backend/tests/test_review_activity.pyindex 9ecc926bb9df..1f5b8e4421b9 100644--- a/products/review_hog/backend/tests/test_review_activity.py+++ b/products/review_hog/backend/tests/test_review_activity.py@@ -6,6 +6,7 @@ from dataclasses import replaceimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import ActivityEnvironmentfrom products.review_hog.backend.reviewer.artefact_content import PRSnapshotArtefact@@ -43,6 +44,7 @@ from products.review_hog.backend.temporal.activities import (split_chunks_activity,)from products.review_hog.backend.temporal.heartbeat import REPORT_HEARTBEAT_INTERVAL, ReviewActivityHeartbeater+from products.tasks.backend.facade.agents import AgentTurnFailedfrom products.tasks.backend.facade.run_config import ReasoningEffort, RuntimeAdapter_MODULE = "products.review_hog.backend.temporal.activities"@@ -308,6 +310,38 @@ async def test_review_chunk_activity_runs_on_the_reports_persisted_arm() -> Noneassert kwargs["workflow_id_prefix"] == f"{env.info.workflow_id}:issues-review-p1-c3".lower()+ "category,expected_type",+ [+ ("upstream_request_rejected", ApplicationError),+ ("agent_error", AgentTurnFailed),+ ("upstream_provider_failure", AgentTurnFailed),+ (None, AgentTurnFailed),+ ],+)+async def test_review_chunk_activity_fails_non_retryably_only_on_non_retryable_agent_categories(+ category: str | None, expected_type: type[Exception]+) -> None:+ failure = AgentTurnFailed("agent failed", category=category, agent_message="agent failed")+ with (+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),+ patch(f"{_MODULE}._prepare_review_prompt", MagicMock(return_value="review-prompt")),+ patch(f"{_MODULE}.load_review_arm", return_value=DEFAULT_REVIEW_ARM),+ patch(f"{_MODULE}.persist_perspective_results"),+ patch(f"{_MODULE}.run_sandbox_review", AsyncMock(side_effect=failure)),+ ):+ with pytest.raises(expected_type) as excinfo:+ await ActivityEnvironment().run(review_chunk_activity, _review_input())++ if isinstance(excinfo.value, ApplicationError):+ assert excinfo.value.non_retryable is True+ assert excinfo.value.type == category+ assert excinfo.value.__cause__ is failure+ else:+ assert excinfo.value is failure++@pytest.mark.asyncioasync def test_blind_spot_unit_scopes_wave_findings_to_its_chunk_and_steps_as_blind_spots() -> None:# A broken (pass, chunk) filter feeds the sweep another chunk's findings or nothing at all.diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.pyindex eee1652f5ab0..2f1eff43d673 100644--- a/products/review_hog/backend/tests/test_temporal_workflow.py+++ b/products/review_hog/backend/tests/test_temporal_workflow.py@@ -16,6 +16,7 @@ import temporalio.workflowfrom parameterized import parameterizedfrom temporalio import activityfrom temporalio.client import WorkflowFailureError+from temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationErrorfrom temporalio.service import RPCErrorfrom temporalio.testing import WorkflowEnvironment@@ -154,6 +155,7 @@ async def _run_full_review_pr_workflow(automatic_reviewed_head_sha: str | None = None,gate_skips: bool = False,fail_gate: bool = False,+ workflow_max_attempts: int | None = None,) -> dict:# Runs the real ReviewPRWorkflow with activity stand-ins, recording what fanned out + published.# already_published / empty_diff drive the early-exit gates; acting_user_id None means the author@@ -486,6 +488,9 @@ async def _run_full_review_pr_workflow(),id=str(uuid.uuid4()),task_queue=task_queue,+ retry_policy=RetryPolicy(maximum_attempts=workflow_max_attempts)+ if workflow_max_attempts is not None+ else None,)except WorkflowFailureError:failed = True@@ -631,6 +636,20 @@ async def test_review_pr_workflow_removes_label_trigger_after_failure():assert recorded["remove_label"] == [7]+async def test_review_pr_workflow_does_not_retry_a_wave_over_the_failure_floor():+ recorded = await _run_full_review_pr_workflow(+ publish=True,+ trigger_source="label",+ fail_review_units=frozenset((p, c) for p in (1, 2, 3) for c in (1, 2)),+ workflow_max_attempts=2,+ )+ assert recorded["failed"] is True+ assert recorded["split"] == [1]+ assert len(recorded["review"]) == 6+ assert recorded["remove_label"] == [7]++@pytest.mark.asyncioasync def test_review_pr_workflow_does_not_remove_label_for_other_triggers():recorded = await _run_full_review_pr_workflow(publish=True, trigger_source="manual")@@ -1079,8 +1098,10 @@ async def test_validate_issues_workflow_fails_above_failure_floor():async def validate_chunk(input: ValidateChunkInput) -> ValidateChunkResult:raise RuntimeError("sandbox boom")- with pytest.raises(WorkflowFailureError):+ with pytest.raises(WorkflowFailureError) as excinfo:await _run_validate_workflow(issue_ids=["1-1-1", "1-2-1"], validate_chunk=validate_chunk)+ assert isinstance(excinfo.value.cause, ApplicationError)+ assert excinfo.value.cause.non_retryable is True@pytest.mark.asynciodiff --git a/products/review_hog/backend/tests/test_validate_activity.py b/products/review_hog/backend/tests/test_validate_activity.pyindex 3d0596d7943b..fc46e7d64e98 100644--- a/products/review_hog/backend/tests/test_validate_activity.py+++ b/products/review_hog/backend/tests/test_validate_activity.py@@ -5,6 +5,7 @@ from collections.abc import Iteratorimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import ActivityEnvironmentfrom products.review_hog.backend.reviewer.artefact_content import PRSnapshotArtefact@@ -21,6 +22,7 @@ from products.review_hog.backend.reviewer.models.issue_validation import IssueVafrom products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRangefrom products.review_hog.backend.reviewer.models.split_pr_into_chunks import Chunk, ChunksList, FileInfofrom products.review_hog.backend.temporal.activities import ValidateChunkInput, validate_chunk_activity+from products.tasks.backend.facade.agents import AgentTurnFailedfrom products.tasks.backend.facade.run_config import ReasoningEffort_MODULE = "products.review_hog.backend.temporal.activities"@@ -171,6 +173,33 @@ async def test_final_attempt_skips_the_failed_turn_and_continues_on_a_fresh_sessassert [call.kwargs["status"] for call in mock_end.await_args_list] == ["failed", "completed"]+async def test_non_retryable_follow_up_turn_failure_fails_the_chunk_even_on_the_final_attempt() -> None:+ ok_issue, rejected_issue, last_issue = _issue(1), _issue(2), _issue(3)+ session = object()+ failure = AgentTurnFailed("rejected", category="upstream_request_rejected", agent_message="rejected")+ mock_start = AsyncMock(return_value=(session, _verdict()))+ mock_end = AsyncMock()+ with (+ _chunk_context(issues=[ok_issue, rejected_issue, last_issue], done={}),+ patch(f"{_MODULE}.persist_verdict", MagicMock(return_value=True)),+ patch(f"{_MODULE}.start_sandbox_session", mock_start),+ patch(f"{_MODULE}.continue_sandbox_session", AsyncMock(side_effect=failure)),+ patch(f"{_MODULE}.end_sandbox_session", mock_end),+ ):+ with pytest.raises(ApplicationError) as excinfo:+ await _env(attempt=VALIDATION_MAX_ATTEMPTS).run(+ validate_chunk_activity, _input([ok_issue, rejected_issue, last_issue])+ )++ assert excinfo.value.non_retryable is True+ assert excinfo.value.__cause__ is failure+ assert mock_start.call_count == 1+ mock_end.assert_awaited_once()+ assert mock_end.await_args is not None+ assert mock_end.await_args.kwargs["status"] == "failed"++@pytest.mark.asyncioasync def test_session_open_failure_raises_even_on_the_final_attempt() -> None:# A session that never opens is the outage signal the failure floor counts — skipping it on the