: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): keep review run api reads light and report triggers (#104983)
Julian Bez4f03e567631f
diff --git a/products/stamphog/backend/facade/api.py b/products/stamphog/backend/facade/api.pyindex 3efd48e98bcd..bbf1d64d9eee 100644--- a/products/stamphog/backend/facade/api.py+++ b/products/stamphog/backend/facade/api.py@@ -13,7 +13,8 @@ from typing import Any, TypeVar, overloadfrom uuid import UUIDfrom django.db import IntegrityError, router, transaction-from django.db.models import Q, QuerySet+from django.db.models import BooleanField, ExpressionWrapper, Q, QuerySet+from django.db.models.fields.json import KeyTransformfrom django.utils import timezoneimport structlog@@ -138,12 +139,12 @@ _MANUAL = Q(output__has_key="manual_review")_RunQS = TypeVar("_RunQS", bound=QuerySet)-def _derive_trigger(obj: ReviewRun) -> ReviewTrigger:+def _derive_trigger(obj: ReviewRun, *, has_inbox_review: bool, has_manual_review: bool) -> ReviewTrigger:"""Why stamphog looked at this PR. The rule itself lives in logic/review_trigger.py, becausethe reviewer invocation has to answer the same question before a run exists to read."""return derive_review_trigger(- has_inbox_review=bool((obj.output or {}).get("inbox_review")),- has_manual_review=bool((obj.output or {}).get("manual_review")),+ has_inbox_review=has_inbox_review,+ has_manual_review=has_manual_review,review_mode=obj.pull_request.repo_config.review_mode,)@@ -167,7 +168,7 @@ def _filter_by_trigger(qs: _RunQS, trigger: str) -> _RunQS:return qs.none()-def _review_run_to_dto(obj: ReviewRun) -> contracts.ReviewRunDTO:+def _build_review_run_dto(obj: ReviewRun, *, output: dict[str, Any], trigger: ReviewTrigger) -> contracts.ReviewRunDTO:return contracts.ReviewRunDTO(id=obj.id,team_id=obj.team_id,@@ -179,12 +180,12 @@ def _review_run_to_dto(obj: ReviewRun) -> contracts.ReviewRunDTO:head_sha=obj.head_sha,status=ReviewRunStatus(obj.status),verdict=ReviewVerdict(obj.verdict),- trigger=_derive_trigger(obj),+ trigger=trigger,title=obj.pull_request.title,author_login=obj.pull_request.author_login,delivery_id=obj.delivery_id,gate_result=obj.gate_result,- output=obj.output,+ output=output,error=obj.error,posted_review_id=obj.posted_review_id,verdict_posted_at=obj.verdict_posted_at,@@ -195,6 +196,44 @@ def _review_run_to_dto(obj: ReviewRun) -> contracts.ReviewRunDTO:)+def _review_run_to_dto(obj: ReviewRun) -> contracts.ReviewRunDTO:+ output = obj.output or {}+ trigger = _derive_trigger(+ obj,+ has_inbox_review=bool(output.get("inbox_review")),+ has_manual_review=bool(output.get("manual_review")),+ )+ return _build_review_run_dto(obj, output=output, trigger=trigger)+++# Retrieve also parses the reviewer's reasoning out of its raw stdout.+_RETRIEVE_OUTPUT_KEYS = (*contracts.REVIEW_RUN_OUTPUT_SUMMARY_KEYS, "reviewer_raw")+++def _slim_review_runs(qs: _RunQS, output_keys: tuple[str, ...]) -> _RunQS:+ """Skip the `output` column and read only `output_keys` and the trigger's provenance flags from it."""+ return qs.defer("output").annotate(+ **{f"slim_output_{key}": KeyTransform(key, "output") for key in output_keys},+ slim_has_inbox_review=ExpressionWrapper(_SELF_DRIVING, output_field=BooleanField()),+ slim_has_manual_review=ExpressionWrapper(_MANUAL, output_field=BooleanField()),+ )+++def _slim_review_run_to_dto(obj: ReviewRun, output_keys: tuple[str, ...]) -> contracts.ReviewRunDTO:+ output = {key: value for key in output_keys if (value := getattr(obj, f"slim_output_{key}")) is not None}+ # _slim_review_runs annotates these, so the model type does not declare them.+ trigger = _derive_trigger(+ obj,+ has_inbox_review=obj.slim_has_inbox_review, # type: ignore[attr-defined]+ has_manual_review=obj.slim_has_manual_review, # type: ignore[attr-defined]+ )+ return _build_review_run_dto(obj, output=output, trigger=trigger)+++def _review_run_list_row_to_dto(obj: ReviewRun) -> contracts.ReviewRunDTO:+ return _slim_review_run_to_dto(obj, contracts.REVIEW_RUN_OUTPUT_SUMMARY_KEYS)++def get_repo_config(team_id: int, repository: str) -> contracts.RepoConfigDTO | None:obj = StamphogRepoConfig.objects.for_team(team_id).filter(repository=repository).first()return _repo_config_to_dto(obj) if obj is not None else None@@ -231,10 +270,10 @@ def has_reviewable_repo_config(team_id: int) -> bool:def get_review_run(team_id: int, review_run_id: str) -> contracts.ReviewRunDTO | None:- obj = (- ReviewRun.objects.for_team(team_id).filter(id=review_run_id).select_related("pull_request__repo_config").first()- )- return _review_run_to_dto(obj) if obj is not None else None+ """One run for the API. Its `output` carries only the summary keys and `reviewer_raw`."""+ qs = ReviewRun.objects.for_team(team_id).filter(id=review_run_id).select_related("pull_request__repo_config")+ obj = _slim_review_runs(qs, _RETRIEVE_OUTPUT_KEYS).first()+ return _slim_review_run_to_dto(obj, _RETRIEVE_OUTPUT_KEYS) if obj is not None else Nonedef _clean_reviewer_text(text: str) -> str:@@ -415,7 +454,7 @@ def list_review_runs(qs = qs.filter(status=status)if trigger:qs = _filter_by_trigger(qs, trigger)- return LazyDTOList(qs, _review_run_to_dto)+ return LazyDTOList(_slim_review_runs(qs, contracts.REVIEW_RUN_OUTPUT_SUMMARY_KEYS), _review_run_list_row_to_dto)def list_pull_requests(diff --git a/products/stamphog/backend/facade/contracts.py b/products/stamphog/backend/facade/contracts.pyindex c57f950d1af4..a36b14bedc6e 100644--- a/products/stamphog/backend/facade/contracts.py+++ b/products/stamphog/backend/facade/contracts.py@@ -86,6 +86,11 @@ class DigestRunDTO:posted_at: datetime | None = None+# The keys of ReviewRun.output the API returns. The rest of the blob holds the PR payload, patches,+# policy files and reviewer stdout, which the API must not expose and a list page must not load.+REVIEW_RUN_OUTPUT_SUMMARY_KEYS = ("stamphog_version", "reviewer_exit_code")++@dataclass(frozen=True)class ReviewRunDTO:"""A single stamphog review attempt against a pull request."""diff --git a/products/stamphog/backend/presentation/serializers.py b/products/stamphog/backend/presentation/serializers.pyindex 7ee1a0a0a81e..29d25e097513 100644--- a/products/stamphog/backend/presentation/serializers.py+++ b/products/stamphog/backend/presentation/serializers.py@@ -454,12 +454,7 @@ class ReviewRunSerializer(DataclassSerializer):def get_output(self, obj: contracts.ReviewRunDTO) -> dict[str, object]:# Explicit allowlist: never echo reviewer_raw / pr / files / policy_files out of the API.raw = obj.output or {}- summary: dict[str, object] = {}- if "stamphog_version" in raw:- summary["stamphog_version"] = raw["stamphog_version"]- if "reviewer_exit_code" in raw:- summary["reviewer_exit_code"] = raw["reviewer_exit_code"]- return summary+ return {key: raw[key] for key in contracts.REVIEW_RUN_OUTPUT_SUMMARY_KEYS if key in raw}@extend_schema_field(_GateResultSummarySerializer)def get_gate_result(self, obj: contracts.ReviewRunDTO) -> dict[str, object]:diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.pyindex e54f718415ef..1c370d53b887 100644--- a/products/stamphog/backend/presentation/views.py+++ b/products/stamphog/backend/presentation/views.py@@ -535,7 +535,13 @@ class ReviewRunViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewSet):OpenApiParameter.QUERY,required=False,enum=[t.value for t in ReviewTrigger],- description="Filter by what caused the run: self_driving, manual, label, or all.",+ description=(+ "Filter by what caused the run. Leave it unset to include runs from every trigger. "+ "'all' is not a wildcard: it matches only runs in repos that review every pull request "+ "event. The other values: 'label' (the repo's trigger label opted the PR in), 'manual' "+ "(someone requested the review through the API or MCP), and 'self_driving' (stamphog "+ "reviewed a bot-authored PR from the inbox)."+ ),),],responses={200: ReviewRunSerializer(many=True)},diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.pyindex 2ca2d631ed1a..5ef6a574c5ca 100644--- a/products/stamphog/backend/temporal/activities.py+++ b/products/stamphog/backend/temporal/activities.py@@ -1212,6 +1212,9 @@ def mark_review_failed(input: MarkReviewFailedInput) -> None:"stamphog_team_id": input.team_id,"stamphog_runtime": "hosted","stamphog_error": first_error_line,+ "stamphog_review_trigger": trigger_for_run(+ output=run.output, review_mode=pull_request.repo_config.review_mode+ ),},)diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.pyindex a5f6ed45af67..2dca79f16217 100644--- a/products/stamphog/backend/tests/test_api.py+++ b/products/stamphog/backend/tests/test_api.py@@ -593,7 +593,8 @@ class TestReviewRunAPI(StamphogTeamScopedTestMixin, APIBaseTest):assert response.status_code == status.HTTP_200_OK, response.contentassert response.json()["results"] == []- def test_output_excludes_raw_repo_content(self) -> None:+ @parameterized.expand([("retrieve",), ("list",)])+ def test_output_excludes_raw_repo_content(self, endpoint: str) -> None:# run.output holds the full PR payload, changed-file patches, default-branch policy files, and# raw reviewer stdout. A project member without repo access can read this endpoint, so the API# must expose only the allowlisted, content-free summary — never the raw repo content.@@ -608,9 +609,14 @@ class TestReviewRunAPI(StamphogTeamScopedTestMixin, APIBaseTest):}run.save(update_fields=["output"])- response = self.client.get(f"{self.url}{run.id}/")- assert response.status_code == status.HTTP_200_OK- output = response.json()["output"]+ if endpoint == "retrieve":+ response = self.client.get(f"{self.url}{run.id}/")+ assert response.status_code == status.HTTP_200_OK+ output = response.json()["output"]+ else:+ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ output = response.json()["results"][0]["output"]assert output == {"stamphog_version": "test-1.0.0", "reviewer_exit_code": 0}for leaked in ("reviewer_raw", "pr", "files", "policy_files"):assert leaked not in outputdiff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.pyindex 94aecf03d08c..0e88bf9c2e8a 100644--- a/products/stamphog/backend/tests/test_integration.py+++ b/products/stamphog/backend/tests/test_integration.py@@ -1148,7 +1148,11 @@ def test_mark_review_failed_captures_failure_event(team, stamphog_chain, raw_errteam_id=team.id, repo_config=repo_config, pr_number=101, author_login="devex-dev")run = ReviewRun.objects.for_team(team.id).create(- team_id=team.id, pull_request=pull_request, head_sha="sha-x", status=ReviewRunStatus.REVIEWING+ team_id=team.id,+ pull_request=pull_request,+ head_sha="sha-x",+ status=ReviewRunStatus.REVIEWING,+ output={"review_trigger": "manual"},)# ph_scoped_capture is a context manager yielding the capture callable, so the patch@@ -1167,6 +1171,7 @@ def test_mark_review_failed_captures_failure_event(team, stamphog_chain, raw_errprops = capture_fn.call_args.kwargs["properties"]assert props["stamphog_repo"] == REPOassert props["stamphog_error"] == expected_stored+ assert props["stamphog_review_trigger"] == "manual"@pytest.mark.django_db(databases=PRODUCT_DATABASES)diff --git a/products/stamphog/frontend/generated/api.schemas.ts b/products/stamphog/frontend/generated/api.schemas.tsindex 42d9313b9264..5dcb8f9b5d94 100644--- a/products/stamphog/frontend/generated/api.schemas.ts+++ b/products/stamphog/frontend/generated/api.schemas.ts@@ -575,7 +575,7 @@ export type StamphogReviewRunsListParams = {*/status?: string/**- * Filter by what caused the run: self_driving, manual, label, or all.+ * Filter by what caused the run. Leave it unset to include runs from every trigger. 'all' is not a wildcard: it matches only runs in repos that review every pull request event. The other values: 'label' (the repo's trigger label opted the PR in), 'manual' (someone requested the review through the API or MCP), and 'self_driving' (stamphog reviewed a bot-authored PR from the inbox).*/trigger?: StamphogReviewRunsListTrigger}diff --git a/products/stamphog/mcp/tools.yaml b/products/stamphog/mcp/tools.yamlindex 934e8ec7f906..76a48fd23035 100644--- a/products/stamphog/mcp/tools.yaml+++ b/products/stamphog/mcp/tools.yaml@@ -174,10 +174,10 @@ tools:title: List stamphog review runsdescription: >List stamphog's automated review runs for pull requests in this project, newest first. Filter by- `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Each run reports its- lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the- reviewer ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to- read it.+ `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Leave `trigger` unset+ unless you want one trigger only: `trigger: all` does not mean every trigger. Each run reports its lifecycle+ `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer+ ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to read it.feature_flag: stamphogresponse:exclude:diff --git a/products/stamphog/packages/pr-approval-agent/review_pr.py b/products/stamphog/packages/pr-approval-agent/review_pr.pyindex 6ed179fd034d..0525f9889232 100644--- a/products/stamphog/packages/pr-approval-agent/review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/review_pr.py@@ -979,6 +979,8 @@ class Pipeline:"stamphog_gate_verdict": gate_verdict,"stamphog_llm_verdict": llm_verdict,"stamphog_final_verdict": self.final_verdict,+ # Empty on a local run: only the hosted runtime knows why the review started.+ "stamphog_review_trigger": self.review_trigger,"stamphog_llm_reasoning": (self.reviewer_output or {}).get("reasoning", ""),"stamphog_llm_risk": (self.reviewer_output or {}).get("risk", ""),"stamphog_llm_issues": (self.reviewer_output or {}).get("issues", []),diff --git a/products/stamphog/packages/pr-approval-agent/test_review_pr.py b/products/stamphog/packages/pr-approval-agent/test_review_pr.pyindex a449e882ca13..dfbe4183f930 100644--- a/products/stamphog/packages/pr-approval-agent/test_review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/test_review_pr.py@@ -666,7 +666,7 @@ def test_capture_review_completed_includes_familiarity_and_provenance(monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", True)monkeypatch.setattr(review_pr, "posthoganalytics", fake_posthog, raising=False)- pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog", review_trigger="manual" if populated else "")pipeline.pr = _fake_pr(head_sha="abc123")if populated:pipeline.classification = {@@ -706,6 +706,7 @@ def test_capture_review_completed_includes_familiarity_and_provenance(assert props["stamphog_commit_count"] == 3assert props["stamphog_generated_by"] == ["PostHog Desktop"]assert props["stamphog_task_ids"] == ["task-1", "task-2"]+ assert props["stamphog_review_trigger"] == "manual"else:assert props["stamphog_owner_teams"] == []assert props["stamphog_familiarity_band"] == ""@@ -713,6 +714,7 @@ def test_capture_review_completed_includes_familiarity_and_provenance(assert props["stamphog_agent_authored"] is Noneassert props["stamphog_generated_by"] == []assert props["stamphog_task_ids"] == []+ assert props["stamphog_review_trigger"] == ""def test_capture_review_completed_merges_server_extras_base_wins(monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 291b87ba4aa2..bbd3143294d2 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -11189,7 +11189,7 @@"feature_flag": "stamphog"},"stamphog-review-runs-list": {- "description": "List stamphog's automated review runs for pull requests in this project, newest first. Filter by `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Each run reports its lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to read it.",+ "description": "List stamphog's automated review runs for pull requests in this project, newest first. Filter by `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Leave `trigger` unset unless you want one trigger only: `trigger: all` does not mean every trigger. Each run reports its lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to read it.","category": "Stamphog","feature": "stamphog","summary": "List stamphog review runs",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex acd5f2a4e3b6..d922ed14dd13 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -11761,7 +11761,7 @@"feature_flag": "stamphog"},"stamphog-review-runs-list": {- "description": "List stamphog's automated review runs for pull requests in this project, newest first. Filter by `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Each run reports its lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to read it.",+ "description": "List stamphog's automated review runs for pull requests in this project, newest first. Filter by `repository`, `pr_number`, or `status` to find why a specific PR got its verdict. Leave `trigger` unset unless you want one trigger only: `trigger: all` does not mean every trigger. Each run reports its lifecycle `status`, final `verdict`, and the deterministic gate outcome (`gate_result`) computed before the reviewer ran. The reviewer's reasoning is null in list results — use `stamphog-review-runs-get` on a run to read it.","category": "Stamphog","feature": "stamphog","summary": "List stamphog review runs",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9eedd6f28133..6e82076babc9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -113520,7 +113520,7 @@ export namespace Schemas {*/status?: string;/**- * Filter by what caused the run: self_driving, manual, label, or all.+ * Filter by what caused the run. Leave it unset to include runs from every trigger. 'all' is not a wildcard: it matches only runs in repos that review every pull request event. The other values: 'label' (the repo's trigger label opted the PR in), 'manual' (someone requested the review through the API or MCP), and 'self_driving' (stamphog reviewed a bot-authored PR from the inbox).*/trigger?: StamphogReviewRunsListTrigger;};diff --git a/services/mcp/src/generated/stamphog/api.ts b/services/mcp/src/generated/stamphog/api.tsindex 8ee75a6d64ff..f3aad6868475 100644--- a/services/mcp/src/generated/stamphog/api.ts+++ b/services/mcp/src/generated/stamphog/api.ts@@ -121,7 +121,9 @@ export const StamphogReviewRunsListQueryParams = () => zod.object({trigger: zod.enum(['all', 'label', 'manual', 'self_driving']).optional()- .describe('Filter by what caused the run: self_driving, manual, label, or all.'),+ .describe(+ "Filter by what caused the run. Leave it unset to include runs from every trigger. 'all' is not a wildcard: it matches only runs in repos that review every pull request event. The other values: 'label' (the repo's trigger label opted the PR in), 'manual' (someone requested the review through the API or MCP), and 'self_driving' (stamphog reviewed a bot-authored PR from the inbox)."+ ),})/**