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): say what actually failed, without leaking what failed on (#91519)

Julian Bez0c44ecbe0cb5
diff --git a/posthog/temporal/common/errors.py b/posthog/temporal/common/errors.py
index fc6b3e65bc42..901ba133f70b 100644
--- a/posthog/temporal/common/errors.py
+++ b/posthog/temporal/common/errors.py
@@ -59,6 +59,18 @@ def resolve_exception_class(exc: BaseException) -> str:
return getattr(cause, "type", None) or type(cause).__name__
+def describe_failure(exc: BaseException) -> str:
+ """Name the exception that failed, for a record kept outside the worker logs.
+
+ ``str()`` of an ``ActivityError`` is always "Activity task failed". ``ApplicationError`` prints
+ its own ``type``, which Temporal sets to the original class name. A plain exception prints no
+ type, so this function adds it. The result goes in a Temporal payload, so it has a size limit.
+ """
+ cause: BaseException = unwrap_temporal_cause(exc) or exc
+ described = str(cause) if isinstance(cause, ApplicationError) else f"{type(cause).__name__}: {cause}"
+ return truncate_for_temporal_payload(described, MAX_ERROR_MESSAGE_CHARS)
+
+
def resolve_error_trace(exc: BaseException) -> str:
cause = unwrap_temporal_cause(exc)
if cause is not None and cause.details and isinstance(cause.details[0], str):
diff --git a/posthog/temporal/common/test_errors.py b/posthog/temporal/common/test_errors.py
index 023842c974bc..ef69c944f6ff 100644
--- a/posthog/temporal/common/test_errors.py
+++ b/posthog/temporal/common/test_errors.py
@@ -6,6 +6,7 @@ from temporalio.exceptions import ActivityError, ApplicationError, ChildWorkflow
from posthog.temporal.common.errors import (
MAX_ERROR_MESSAGE_CHARS,
MAX_ERROR_TRACE_CHARS,
+ describe_failure,
resolve_failure_type,
truncate_for_temporal_payload,
unwrap_temporal_cause,
@@ -104,3 +105,30 @@ def test_resolve_failure_type(exc: BaseException, expected: str) -> None:
resolved = resolve_failure_type(exc)
assert resolved == expected
assert isinstance(resolved, str)
+
+
+ "exc,expected",
+ [
+ # ApplicationError renders its own `type` prefix, so adding one would double it.
+ (ApplicationError("boom", type="ProgrammingError"), "ProgrammingError: boom"),
+ (_activity_error(ApplicationError("boom", type="ProgrammingError")), "ProgrammingError: boom"),
+ (
+ _child_workflow_error(_activity_error(ApplicationError("boom", type="ProgrammingError"))),
+ "ProgrammingError: boom",
+ ),
+ # A plain exception carries its type nowhere in its text, so describe_failure supplies it.
+ (ValueError("boom"), "ValueError: boom"),
+ # Without unwrapping, this is the useless "Activity task failed" the helper exists to replace.
+ (_activity_error(ValueError("boom")), "ActivityError: activity failed"),
+ ],
+ ids=["bare_application_error", "activity_error", "nested_wrappers", "plain_exception", "no_application_cause"],
+)
+def test_describe_failure(exc: BaseException, expected: str) -> None:
+ assert describe_failure(exc) == expected
+
+
+def test_describe_failure_bounds_the_message_for_the_payload() -> None:
+ described = describe_failure(ApplicationError("x" * (MAX_ERROR_MESSAGE_CHARS * 2), type="BigError"))
+ assert len(described) < MAX_ERROR_MESSAGE_CHARS + 100
+ assert described.endswith("chars)")
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index a70b7536148a..c56a21b4f742 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -69,6 +69,7 @@ from products.stamphog.backend.temporal.constants import (
STAMPHOG_SANDBOX_OWNERS_DIR,
STAMPHOG_SANDBOX_REPO_DIR,
STAMPHOG_TRUSTED_REACTOR_BOTS,
+ SandboxPhaseError,
)
from products.tasks.backend.facade.sandbox import (
SandboxBase,
@@ -483,37 +484,68 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
environment_variables=environment,
outbound_domain_allowlist=_sandbox_egress_allowlist(),
)
- sandbox = sandbox_class.create(config)
+ # The steps above cost nothing and keep their own exception type. From here the run makes a
+ # sandbox and can run the reviewer, so failures raise SandboxPhaseError, which the retry policy
+ # excludes. Both statements stay outside the try below, so the refusal keeps its own type and a
+ # failed write stays retryable.
+ #
+ # Temporal applies the start-to-close timeout and retries a lost worker. Neither path raises a
+ # type this code can mark, so the claim is what stops a second sandbox. Read it from the writer,
+ # because a stalled attempt holds a copy from before its replacement wrote. Read and then write
+ # is not atomic: two attempts in the same instant both pass. A column and a conditional update
+ # would close that.
+ latest_output = (
+ ReviewRun.objects.for_team(input.team_id)
+ .using(router.db_for_write(ReviewRun))
+ .filter(id=run.id)
+ .values_list("output", flat=True)
+ .first()
+ ) or {}
+ if latest_output.get("sandbox_started_at"):
+ raise SandboxPhaseError("an earlier attempt already provisioned a sandbox for this run")
+ run.output = {**latest_output, "sandbox_started_at": timezone.now().isoformat()}
+ run.save(update_fields=["output", "updated_at"])
+
try:
- _clone_pr(sandbox, repo, base_sha, run.head_sha, run.pull_request.pr_number, token)
- _inject_policy_files(sandbox, policy_files)
- _ship_engine(sandbox)
- _write_context(sandbox, invocation)
-
- command = f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && {_harden_reviewer_command(invocation.command)}"
- result = sandbox.execute(command, timeout_seconds=25 * 60)
- finally:
- # A destroy failure must not mask a completed review — the verdict below still has to be
- # persisted and posted. An orphaned sandbox self-terminates when SandboxConfig.ttl_seconds expires.
+ sandbox = sandbox_class.create(config)
try:
- sandbox.destroy()
- except Exception:
- activity.logger.exception(f"Failed to destroy sandbox for run {run.id}")
-
- # Scrub stdout before persisting: it can echo the LLM keys the sandbox holds, and it is
- # both stored on run.output and re-read verbatim to render the verdict posted to GitHub.
- run.output = {
- **(run.output or {}),
- "reviewer_raw": _scrub_credentials(result.stdout, token, gateway_token),
- "reviewer_exit_code": result.exit_code,
- }
- run.save(update_fields=["output", "updated_at"])
+ _clone_pr(sandbox, repo, base_sha, run.head_sha, run.pull_request.pr_number, token)
+ _inject_policy_files(sandbox, policy_files)
+ _ship_engine(sandbox)
+ _write_context(sandbox, invocation)
+
+ command = f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && {_harden_reviewer_command(invocation.command)}"
+ result = sandbox.execute(command, timeout_seconds=25 * 60)
+ finally:
+ # A destroy failure must not mask a completed review — the verdict below still has to be
+ # persisted and posted. An orphaned sandbox self-terminates when SandboxConfig.ttl_seconds expires.
+ try:
+ sandbox.destroy()
+ except Exception:
+ activity.logger.exception(f"Failed to destroy sandbox for run {run.id}")
+
+ # Scrub stdout before persisting: it can echo the LLM keys the sandbox holds, and it is
+ # both stored on run.output and re-read verbatim to render the verdict posted to GitHub.
+ run.output = {
+ **(run.output or {}),
+ "reviewer_raw": _scrub_credentials(result.stdout, token, gateway_token),
+ "reviewer_exit_code": result.exit_code,
+ }
+ run.save(update_fields=["output", "updated_at"])
- if result.exit_code != 0:
- raise RuntimeError(
- f"Reviewer exited with code {result.exit_code}: "
- f"{_scrub_credentials(result.stderr, token, gateway_token)[:500]}"
- )
+ if result.exit_code != 0:
+ # The reviewer reads an untrusted PR head, so its stderr can contain repository content.
+ # This message reaches run.error, so keep the stderr in the worker log only.
+ activity.logger.error(
+ f"Reviewer exited with code {result.exit_code} for run {run.id}: "
+ f"{_scrub_credentials(result.stderr, token, gateway_token)[:500]}"
+ )
+ raise RuntimeError(f"reviewer exited with code {result.exit_code}")
+ except Exception as exc:
+ # Give the type only. Every step in this phase touches the sandbox, and anyone with
+ # stamphog:read can read run.error without access to the repository. The setup phase above
+ # keeps its text, because it fails on our own infrastructure and must stay diagnosable.
+ raise SandboxPhaseError(f"the sandbox phase failed with {type(exc).__name__}") from exc
activity.logger.info(f"Reviewer completed for run {run.id}")
return {"exit_code": result.exit_code}
@@ -1109,7 +1141,10 @@ def _overlay_policy_yaml(repo: str, default_text: str, repo_text: str | None) ->
try:
overlay = yaml.safe_load(repo_text)
except yaml.YAMLError as exc:
- raise RuntimeError(f"repo {repo} has malformed YAML in .stamphog/policy.yml: {exc}") from exc
+ # PyYAML puts the bad tag on the first line, and run.error keeps that line. Anyone with
+ # stamphog:read can read it without access to the repository, so log the parser text instead.
+ activity.logger.error(f"Malformed YAML in .stamphog/policy.yml for {repo}: {exc}")
+ raise RuntimeError(f"repo {repo} has malformed YAML in .stamphog/policy.yml") from exc
if not isinstance(overlay, dict):
raise RuntimeError(f"repo {repo} .stamphog/policy.yml must be a YAML mapping to overlay the defaults")
merged = {**yaml.safe_load(default_text), **overlay}
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index d44eaac26ffb..883362ac9880 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -80,7 +80,16 @@ ACTIVITY_RETRY_POLICY = RetryPolicy(
maximum_interval=timedelta(minutes=1),
)
-# The sandbox review provisions a box, clones the repo, and runs the reviewer agent —
-# expensive and side-effecting, so a transient failure fails the run rather than
-# silently paying for it twice. The workflow-level wrapper marks the run FAILED.
+
+class SandboxPhaseError(Exception):
+ """Marks the paid phase of the review activity: this attempt made a sandbox, or found the claim
+ of an earlier one. SANDBOX_RETRY_POLICY excludes this type, so no run pays for a review twice.
+ """
+
+
+# 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)
diff --git a/products/stamphog/backend/temporal/workflow.py b/products/stamphog/backend/temporal/workflow.py
index 88c2550baf69..c8a5b5dcc437 100644
--- a/products/stamphog/backend/temporal/workflow.py
+++ b/products/stamphog/backend/temporal/workflow.py
@@ -16,6 +16,7 @@ import temporalio.workflow
from temporalio import workflow
from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.errors import describe_failure
from products.stamphog.backend.temporal.constants import (
ACTIVITY_RETRY_POLICY,
@@ -119,7 +120,7 @@ class StamphogReviewWorkflow(PostHogWorkflow):
MarkReviewFailedInput(
review_run_id=input.review_run_id,
team_id=input.team_id,
- error=str(e),
+ error=describe_failure(e),
),
start_to_close_timeout=MARK_FAILED_TIMEOUT,
retry_policy=ACTIVITY_RETRY_POLICY,
diff --git a/products/stamphog/backend/tests/conftest.py b/products/stamphog/backend/tests/conftest.py
index 08f98e952f93..83bf553a7d9a 100644
--- a/products/stamphog/backend/tests/conftest.py
+++ b/products/stamphog/backend/tests/conftest.py
@@ -14,6 +14,7 @@ from cryptography.hazmat.primitives.asymmetric import rsa
from posthog.models import OAuthApplication
from posthog.models.scoping import team_scope
+from posthog.temporal.common.errors import describe_failure
from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, ARRAY_APP_CLIENT_ID_EU, ARRAY_APP_CLIENT_ID_US
from products.stamphog.backend.temporal.activities import (
@@ -123,7 +124,10 @@ def _inline_review_workflow(review_run_id: str, team_id: int) -> None:
_run_activity(run_review_in_sandbox, inp)
_run_activity(post_verdict, inp)
except Exception as e: # noqa: BLE001 — mirror the workflow's failure path
- _run_activity(mark_review_failed, MarkReviewFailedInput(review_run_id, team_id, str(e)))
+ _run_activity(
+ mark_review_failed,
+ MarkReviewFailedInput(review_run_id, team_id, describe_failure(e)),
+ )
@dataclass
diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.py
index af2f61a1cc34..deafa1858eb8 100644
--- a/products/stamphog/backend/tests/fakes.py
+++ b/products/stamphog/backend/tests/fakes.py
@@ -522,6 +522,9 @@ def make_fake_sandbox_class(engine_output: str, write_sink: list[tuple[str, byte
class _FakeSandbox:
# A test can set this on the class to make teardown blow up (destroy-must-not-mask coverage).
destroy_error: Exception | None = None
+ # A test can set this to make provisioning blow up, which is the first step of the review's
+ # paid phase (retry-boundary coverage).
+ create_error: Exception | None = None
# Every SandboxConfig passed to create(), so a test can assert what the sandbox was given
# (environment variables, egress allowlist).
created_configs: list[Any] = []
@@ -529,6 +532,8 @@ def make_fake_sandbox_class(engine_output: str, write_sink: list[tuple[str, byte
@classmethod
def create(cls, config: Any) -> _FakeSandbox:
cls.created_configs.append(config)
+ if cls.create_error is not None:
+ raise cls.create_error
return cls()
def execute(self, command: str, timeout_seconds: int | None = None) -> FakeExecResult:
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 1a47647300b0..6c02148f15f2 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -44,8 +44,13 @@ from products.stamphog.backend.temporal.activities import (
list_in_flight_reviewer_bots,
mark_review_failed,
post_verdict,
+ run_review_in_sandbox,
+)
+from products.stamphog.backend.temporal.constants import (
+ STAMPHOG_SANDBOX_CONTEXT_PATH,
+ STAMPHOG_SANDBOX_REPO_DIR,
+ SandboxPhaseError,
)
-from products.stamphog.backend.temporal.constants import STAMPHOG_SANDBOX_CONTEXT_PATH, STAMPHOG_SANDBOX_REPO_DIR
from products.stamphog.backend.tests import fakes
from products.stamphog.backend.tests.conftest import PRODUCT_DATABASES, StamphogChain, _run_activity
from products.tasks.backend.models import Task, TaskRun
@@ -227,6 +232,65 @@ def test_sandbox_destroy_failure_does_not_mask_a_completed_review(team, stamphog
assert any(w["kind"] == "approve_review" for w in recorder.github_writes)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_failure_once_the_sandbox_exists_is_not_retried(team, stamphog_chain: StamphogChain) -> None:
+ # Provisioning the box is the first paid step, so a failure from there on must reach Temporal as
+ # SandboxPhaseError. Without the marker SANDBOX_RETRY_POLICY would run the reviewer agent again
+ # and bill a second time for one review.
+ _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ author, head_sha = "devex-dev", "sha110a"
+ recorder.register_pr(REPO, 110, _pr_object(110, author, head_sha), _pr_files())
+ recorder.policy_files[".stamphog/policy.yml"] = "version: 1\n"
+ stamphog_chain.sandbox_class.create_error = RuntimeError("modal refused the box")
+
+ status = stamphog_chain.post_webhook(_opened_event(110, author, head_sha), delivery_id=str(uuid.uuid4()))
+ assert status == 202
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.FAILED
+ # The record names the marker and the failing type, and carries nothing from the sandbox: run.error
+ # is readable with stamphog:read by people who need no access to the repository, and everything in
+ # this phase derives from an untrusted PR head.
+ assert run.error == "SandboxPhaseError: the sandbox phase failed with RuntimeError"
+ assert "modal refused the box" not in (run.error or "")
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_second_attempt_never_provisions_a_second_sandbox(team, stamphog_chain: StamphogChain) -> None:
+ # Temporal enforces the start-to-close timeout itself and retries a lost worker, and neither path
+ # raises anything the SandboxPhaseError marker can catch. Only the run-level stamp stops such a
+ # retry from provisioning a second box and billing a second reviewer agent.
+ _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ author, head_sha = "devex-dev", "sha111a"
+ recorder.register_pr(REPO, 111, _pr_object(111, author, head_sha), _pr_files())
+ recorder.policy_files[".stamphog/policy.yml"] = "version: 1\n"
+ stamphog_chain.sandbox_class.create_error = RuntimeError("modal refused the box")
+
+ stamphog_chain.post_webhook(_opened_event(111, author, head_sha), delivery_id=str(uuid.uuid4()))
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert len(stamphog_chain.sandbox_class.created_configs) == 1
+
+ # Clearing the scripted failure is what makes this prove the stamp: a second attempt would
+ # otherwise provision successfully and run the reviewer again.
+ stamphog_chain.sandbox_class.create_error = None
+ with pytest.raises(SandboxPhaseError):
+ _run_activity(run_review_in_sandbox, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+ assert len(stamphog_chain.sandbox_class.created_configs) == 1
+
+
+def test_malformed_repo_policy_keeps_the_parser_text_out_of_the_error() -> None:
+ # PyYAML names the offending construct on its first line, and that line is what mark_review_failed
+ # persists into run.error, which is readable with stamphog:read by people who need no access to
+ # the repository. The default branch it comes from is private to that repository.
+ with pytest.raises(RuntimeError) as raised:
+ activities._overlay_policy_yaml("acme/widgets", "version: 1\n", "!a-private-internal-tag {}\n")
+
+ assert "a-private-internal-tag" not in str(raised.value)
+ assert ".stamphog/policy.yml" in str(raised.value)
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_sandbox_gets_minted_short_lived_credential_and_closed_egress(
team, user, stamphog_chain: StamphogChain
@@ -382,6 +446,9 @@ def test_hosted_review_fails_closed_without_gateway_instead_of_anthropic_fallbac
assert run.status == ReviewRunStatus.FAILED
assert "gateway" in (run.error or "").lower()
assert not stamphog_chain.sandbox_class.created_configs # no sandbox was ever provisioned
+ # Nothing was paid for, so this failure must stay retryable: SANDBOX_RETRY_POLICY gives another
+ # attempt to every type except SandboxPhaseError.
+ assert not (run.error or "").startswith("SandboxPhaseError")
@pytest.mark.django_db(databases=PRODUCT_DATABASES)