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.

perf(stamphog): overlap the sandbox and clone with the context fetch (#106570)

Julian Bez6f62f8fc42d5
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 2cea41138851..95c7654c6b3b 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -99,7 +99,9 @@ add a read-then-act path, pin it; this class of bug has been found on five separ
to `product=aio_stamphog` and `obo=<customer team>`, capped at `cap_usd=5` and `ttl_seconds=3600`,
acting as the repo's connecting user. The `phs_` never enters the sandbox; a mint failure fails
the run (no shared-key fallback); the worker revokes the token once the reviewer returns,
- without waiting for the sandbox teardown. Do not widen the cap or TTL without a run-cost reason: they bound what a prompt-injected reviewer can
+ without waiting for the sandbox teardown. The review mints the token after the sandbox exists, so
+ the token reaches it as a file (`STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH`), never in the creation env
+ or a command line. Do not widen the cap or TTL without a run-cost reason: they bound what a prompt-injected reviewer can
spend with a leaked token.
- The raw-Anthropic fallback exists for a local `review_pr.py` run only; hosted runs fail closed
without a gateway. No `ANTHROPIC_API_KEY` may enter the sandbox environment.
@@ -270,6 +272,8 @@ T2-never with it, so it answers False for every PR it exists to catch.
registry-completeness test guards this, don't bypass it.
- Workflow bodies follow the repo-wide determinism rules (`workflow.patched()` for new commands).
- Activity payloads stay small; large context rides in `run.output`, not through the workflow.
+- The sandbox start and checkout run beside the context fetch, the pre-check and the bot polls, so every activity that can overlap them writes `run.output` through `_merge_run_output` (a JSONB `||` merge), never a read-modify-write `save()` from a copy loaded earlier. A stale copy drops the other activity's keys, including the sandbox claim that stops a retry from paying for a second sandbox. The merge replaces a key whole, so the sandbox start and checkout record their step timings under their own keys, not in `timings_ms`.
+- No activity waits inside for another activity's write. A waiting activity holds a worker thread and an activity slot, and enough of them starve the activities they wait for. Put the wait in the workflow and split the activity at it.
## Tests
diff --git a/products/stamphog/README.md b/products/stamphog/README.md
index a5639ecf954e..5ff98d8c17ac 100644
--- a/products/stamphog/README.md
+++ b/products/stamphog/README.md
@@ -131,10 +131,11 @@ Why the digest works this way: [`docs/digest.md`](docs/digest.md).
Hosted flow: webhook → Celery (`backend/tasks/tasks.py`) → Temporal (`backend/temporal/workflow.py`) → sandboxed engine → verdict posted back (`post_verdict`).
The workflow dismisses stale approvals first, waits out other in-flight reviewer bots, then reviews.
+The sandbox starts right after the stale-approval sweep and fetches the PR head while the context loads. The checkout starts once the context is stored and runs beside the pre-check and the bot wait. Each step is its own activity, and the workflow does every wait between them. A pre-check verdict posts first, and the workflow then tears down the unused sandbox.
Before the wait, the worker runs the engine's gates alone on the fetched context (`review_local.py --pregate`).
The server also reads every `AGENT_APPROVALS.md` that governs a changed file at the PR head, so the pre-check budgets the size gate like the sandbox does.
-When a gate refusal is certain to hold in the full review, stamphog posts it right away with a short LLM note on what the author can do, and skips the wait and the sandbox.
-A migration whose `Migration risk` check has not reported gets the same WAIT the full review would give, without the sandbox.
+When a gate refusal is certain to hold in the full review, stamphog posts it right away with a short LLM note on what the author can do, and skips the wait and the sandbox review.
+A migration whose `Migration risk` check has not reported gets the same WAIT the full review would give, without the sandbox review.
Anything less certain, such as a PR with renamed files, a dependency manifest next to a pending migration, or folder files that could not be read, gets the full review.
A dismissed approval is also hidden on the PR timeline as outdated, so superseded reviews do not pile up. Hiding is best-effort and never blocks the dismissal.
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index 5b5c829422c7..19c5f513531b 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -31,14 +31,17 @@ from collections.abc import Callable, Iterator, Sequence
from concurrent.futures import Future, ThreadPoolExecutor
from contextlib import contextmanager
from dataclasses import dataclass, field
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from email.utils import parsedate_to_datetime
from pathlib import Path, PurePosixPath
-from typing import Any
+from typing import Any, Literal
from urllib.parse import urlparse
from django.conf import settings
+from django.core.serializers.json import DjangoJSONEncoder
from django.db import router
+from django.db.models import F, Func, JSONField, Value
+from django.db.models.functions import Cast, Coalesce
from django.utils import timezone
from django.utils.dateparse import parse_datetime
@@ -90,7 +93,9 @@ from products.stamphog.backend.temporal.constants import (
PREFETCH_DIFF_BLOBS_TIMEOUT_SECONDS,
REVIEWER_TIMEOUT_SECONDS,
RUN_REVIEW_TIMEOUT,
+ SANDBOX_CHECKOUT_TIMEOUT,
SANDBOX_PHASE_RESERVE_SECONDS,
+ SANDBOX_START_TIMEOUT,
STAMPHOG_BOT_EYES_MAX_AGE_SECONDS,
STAMPHOG_OPTIONAL_POLICY_PATHS,
STAMPHOG_POLICY_ENTRYPOINT,
@@ -99,6 +104,7 @@ from products.stamphog.backend.temporal.constants import (
STAMPHOG_REVIEWHOG_LABEL,
STAMPHOG_SANDBOX_CONTEXT_PATH,
STAMPHOG_SANDBOX_ENGINE_DIR,
+ STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH,
STAMPHOG_SANDBOX_OWNERS_DIR,
STAMPHOG_SANDBOX_PAYLOAD_PATH,
STAMPHOG_SANDBOX_REPO_DIR,
@@ -106,8 +112,10 @@ from products.stamphog.backend.temporal.constants import (
SandboxPhaseError,
)
from products.tasks.backend.facade.sandbox import (
+ ExecutionResult,
SandboxBase,
SandboxConfig,
+ SandboxNotFoundError,
SandboxTemplate,
get_sandbox_class_for_backend,
)
@@ -117,6 +125,7 @@ _OWNERS_RELATIVE_DIR = PurePosixPath(STAMPHOG_SANDBOX_OWNERS_DIR).relative_to(ST
_OWNERS_PACKAGE_RELATIVE_DIR = f"{_OWNERS_RELATIVE_DIR}/owners_yaml"
_CONTEXT_RELATIVE_PATH = PurePosixPath(STAMPHOG_SANDBOX_CONTEXT_PATH).relative_to(STAMPHOG_SANDBOX_REPO_DIR).as_posix()
+
# The context reads are a dozen GitHub round trips plus the familiarity reads, which run their own pool.
_CONTEXT_FETCH_WORKERS = 8
@@ -133,6 +142,12 @@ class StamphogReviewInput:
team_id: int
+@dataclass(frozen=False)
+class ReviewSandboxInput(StamphogReviewInput):
+ sandbox_id: str
+ merge_base_sha: str = ""
+
+
@dataclass
class MarkReviewFailedInput:
review_run_id: str
@@ -152,6 +167,31 @@ def _load_run(input: StamphogReviewInput) -> ReviewRun:
)
+def _output_merge(updates: dict[str, Any]) -> Func:
+ """Postgres ``output || updates``: a top-level key merge that the database performs."""
+ return Func(
+ Coalesce(F("output"), Cast(Value("{}"), output_field=JSONField())),
+ Cast(Value(json.dumps(updates, cls=DjangoJSONEncoder)), output_field=JSONField()),
+ template="%(expressions)s",
+ arg_joiner=" || ",
+ output_field=JSONField(),
+ )
+
+
+def _merge_run_output(run: ReviewRun, updates: dict[str, Any]) -> None:
+ """Merge ``updates`` into the stored ``run.output`` in one statement, and into ``run.output``.
+
+ The sandbox start and checkout run beside the context fetch, the pre-check and the bot polls, and
+ each of them writes keys into the same JSON column. A read-modify-write from a copy loaded earlier
+ would drop the keys another activity wrote in between, such as the sandbox claim. The JSONB ``||``
+ merge keeps every key it does not name.
+ """
+ ReviewRun.objects.for_team(run.team_id).using(router.db_for_write(ReviewRun)).filter(id=run.id).update(
+ output=_output_merge(updates), updated_at=timezone.now()
+ )
+ run.output = {**(run.output or {}), **updates}
+
+
# aio_ continues the series the Action-era runs emitted; the engine blob carries the same word.
STAMPHOG_AI_PRODUCT = "aio_stamphog"
# The cap bounds what a leaked token can spend; the TTL must outlive the 30-minute review activity.
@@ -335,28 +375,14 @@ def _engine_analytics_environment(properties: dict[str, object]) -> dict[str, st
return env
-def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConfig]:
- """Environment for the in-sandbox reviewer.
-
- The sandbox holds no GitHub token by design, and no long-lived LLM credential either: the only
- secret it receives is a per-run minted gateway token. A gateway is mandatory for hosted runs —
- the engine's raw-Anthropic fallback exists for a local run, where the env is the developer's
- own, and an org-wide Anthropic key must never ride into a sandbox that runs an LLM over untrusted
- PR content.
+def _hosted_gateway() -> AIGatewayConfig:
+ """The ai-gateway every hosted review calls.
- ``AI_GATEWAY_URL`` and ``AI_GATEWAY_API_KEY`` name the Go ai-gateway and the worker's ``phs_``;
- the token is a per-run ``phe_`` the caller revokes once the sandbox is gone. The sandbox sees
- the same two names with the token in place of the key.
+ A gateway is mandatory for hosted runs — the engine's raw-Anthropic fallback exists for a local
+ run, where the env is the developer's own, and an org-wide Anthropic key must never ride into a
+ sandbox that runs an LLM over untrusted PR content.
- POSTHOG_API_KEY/POSTHOG_HOST let the engine emit its stamphog_review_completed event and LLM
- traces from inside the sandbox. The capture key is a public project write token — the same class of
- token every frontend snippet ships — so its blast radius is event spam, not data access; it's still
- added to llm_env_secrets so persisted output stays tidy. STAMPHOG_EXTRA_PROPERTIES stamps the
- hosted runtime/team/run context onto those events.
-
- NETWORK_RESTRICTED_AGENT_ENV stops the Claude Code CLI under the Agent SDK from calling its own
- telemetry, error-reporting and update hosts. The egress allowlist blocks them, and a blocked call
- waits for its timeout before the CLI exits.
+ ``AI_GATEWAY_URL`` and ``AI_GATEWAY_API_KEY`` name the Go ai-gateway and the worker's ``phs_``.
"""
gateway = resolve_ai_gateway_config()
if gateway is None:
@@ -368,14 +394,34 @@ def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConf
"AI_GATEWAY_API_KEY is set but AI_GATEWAY_URL is the legacy stamphog route; "
"the ai-gateway key belongs with the ai-gateway URL"
)
- token = _mint_reviewer_scoped_token(gateway, run, _connected_user(run))
+ return gateway
+
+
+def _reviewer_environment(run: ReviewRun, gateway: AIGatewayConfig) -> dict[str, str]:
+ """Environment the review sandbox is created with.
+
+ The sandbox holds no GitHub token by design, and no long-lived LLM credential either: the only
+ secret it receives is a per-run minted ``phe_`` gateway token, which the caller revokes once the
+ review is done. That token is not in this environment. The sandbox exists before the review
+ mints it, so _run_reviewer writes it to STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH, and the reviewer
+ command reads it into ``AI_GATEWAY_API_KEY``, the name the engine expects.
+
+ POSTHOG_API_KEY/POSTHOG_HOST let the engine emit its stamphog_review_completed event and LLM
+ traces from inside the sandbox. The capture key is a public project write token — the same class of
+ token every frontend snippet ships — so its blast radius is event spam, not data access; it's still
+ added to llm_env_secrets so persisted output stays tidy. STAMPHOG_EXTRA_PROPERTIES stamps the
+ hosted runtime/team/run context onto those events.
+
+ NETWORK_RESTRICTED_AGENT_ENV stops the Claude Code CLI under the Agent SDK from calling its own
+ telemetry, error-reporting and update hosts. The egress allowlist blocks them, and a blocked call
+ waits for its timeout before the CLI exits.
+ """
env = {
"STAMPHOG_REPO_DIR": STAMPHOG_SANDBOX_REPO_DIR,
"AI_GATEWAY_URL": gateway.url,
- "AI_GATEWAY_API_KEY": token,
**NETWORK_RESTRICTED_AGENT_ENV,
}
- return {**env, **_engine_analytics_environment(_hosted_analytics_properties(run))}, gateway
+ return {**env, **_engine_analytics_environment(_hosted_analytics_properties(run))}
def _sandbox_egress_allowlist(gateway_url: str) -> list[str]:
@@ -525,8 +571,7 @@ def fetch_review_context(input: StamphogReviewInput) -> dict:
policy_files[path] = content
history: ReviewHistory = history_future.result()
- run.output = {
- **(run.output or {}),
+ context = {
"pr": pr,
"files": files,
"reviews": reviews_future.result(),
@@ -554,11 +599,11 @@ def fetch_review_context(input: StamphogReviewInput) -> dict:
# A failed read raises out of its result() above and fails the activity, which retries. The
# other reads are abandoned rather than awaited.
executor.shutdown(wait=False, cancel_futures=True)
- run.save(update_fields=["output", "updated_at"])
+ _merge_run_output(run, context)
activity.logger.info(
f"Fetched review context for run {run.id} (pr #{number}, {len(files)} files); "
- f"timings: {run.output['context_timings_ms']}"
+ f"timings: {context['context_timings_ms']}"
)
return {"pr_number": number, "file_count": len(files), "head_sha": run.head_sha}
@@ -662,8 +707,7 @@ def list_in_flight_reviewer_bots(input: StamphogReviewInput) -> dict:
"polls": int(bot_wait.get("polls") or 0) + 1,
"ms": int((now - first_started_at).total_seconds() * 1000),
}
- run.output = {**(run.output or {}), "pr_reactions": reactions, "bot_wait": bot_wait}
- run.save(update_fields=["output", "updated_at"])
+ _merge_run_output(run, {"pr_reactions": reactions, "bot_wait": bot_wait})
# Exclude stamphog's own bot login: STAMPHOG_TRUSTED_REACTOR_BOTS is a hardcoded set of OTHER
# reviewer bots' logins, so this app's own 👀 (posted by signal_review_started) can't collide
@@ -686,17 +730,17 @@ def list_in_flight_reviewer_bots(input: StamphogReviewInput) -> dict:
return {"in_flight": in_flight}
-def _sandbox_deadline() -> float:
- """Monotonic time the sandbox phase has to finish by, measured from Temporal's own clock.
+def _sandbox_deadline(timeout: timedelta) -> float:
+ """Monotonic time a sandbox activity has to finish by, measured from Temporal's own clock.
- Temporal starts RUN_REVIEW_TIMEOUT when it hands the activity task to the worker, which can be
+ Temporal starts the activity's ``timeout`` when it hands the activity task to the worker, which can be
well before this code runs: ``@asyncify`` queues the synchronous body on an executor, and the
run load, token fetch and invocation build all happen before a sandbox exists. Anchoring on
``started_time`` charges every one of those to the budget, so no step is granted time the
activity itself does not have. A missing ``started_time`` falls back to the full budget, which
is the behaviour of a worker that is not queueing.
"""
- budget = RUN_REVIEW_TIMEOUT.total_seconds() - SANDBOX_PHASE_RESERVE_SECONDS
+ budget = timeout.total_seconds() - SANDBOX_PHASE_RESERVE_SECONDS
try:
elapsed = (datetime.now(UTC) - activity.info().started_time).total_seconds()
except Exception:
@@ -802,8 +846,7 @@ def _fast_refusal_summary(run: ReviewRun, outcome: PregateOutcome) -> str | None
def _save_pregate_outcome(run: ReviewRun, pregate_outcome: str) -> None:
- run.output = {**(run.output or {}), "pregate_outcome": pregate_outcome}
- run.save(update_fields=["output", "updated_at"])
+ _merge_run_output(run, {"pregate_outcome": pregate_outcome})
def _refuse_on_pre_gates(run: ReviewRun) -> dict:
@@ -847,15 +890,16 @@ def _refuse_on_pre_gates(run: ReviewRun) -> dict:
# The same last-line JSON contract the sandbox prints, so post_verdict parses it unchanged. The
# summary is LLM text over PR content, so it gets the same scrub as the sandbox's stdout.
- run.output = {
- **(run.output or {}),
- "reviewer_raw": scrub_credentials(json.dumps(final.result)),
- "reviewer_exit_code": 0,
- "timings_ms": timer.timings_ms,
- "fast_path": True,
- "pregate_outcome": f"final:{final.result.get('final_verdict')}",
- }
- run.save(update_fields=["output", "updated_at"])
+ _merge_run_output(
+ run,
+ {
+ "reviewer_raw": scrub_credentials(json.dumps(final.result)),
+ "reviewer_exit_code": 0,
+ "timings_ms": timer.timings_ms,
+ "fast_path": True,
+ "pregate_outcome": f"final:{final.result.get('final_verdict')}",
+ },
+ )
activity.logger.info(f"Pre-gate verdict for run {run.id}; step timings: {timer.timings_ms}")
return {"refused": True}
@@ -884,27 +928,168 @@ def refuse_on_pre_gates(input: StamphogReviewInput) -> dict:
return {"refused": False, "skipped": "error"}
-@asyncify
-def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
- """Provision a sandbox, clone the PR, run the full engine offline, stash its raw output."""
- deadline = _sandbox_deadline()
+def _save_step_timings(run: ReviewRun, key: str, timings_ms: dict[str, int]) -> None:
+ """Store step timings. Best effort: a failed write must not fail a review that already ran."""
+ try:
+ _merge_run_output(run, {key: timings_ms})
+ except Exception:
+ activity.logger.exception(f"Failed to store {key} for run {run.id}")
+
+
+def _begin_sandbox_phase(input: StamphogReviewInput) -> ReviewRun | None:
+ """Load the run and flip it to REVIEWING. None when the run is superseded or already terminal."""
run = _load_run(input)
# A newer relevant delivery for the same PR may have superseded this run while it queued — even
# one that didn't move the head SHA (e.g. `labeled`, `ready_for_review`). Bail before flipping the
# status back to REVIEWING: reviving it here would defeat the post_verdict superseded guard (which
- # keys off status) and let a stale run post its verdict. Skip the sandbox entirely.
- if run.status == ReviewRunStatus.SUPERSEDED:
- activity.logger.info(f"Skipping sandbox for superseded run {run.id}")
- return {"skipped": "superseded"}
+ # keys off status) and let a stale run post its verdict. Skip the sandbox entirely. The sandbox
+ # start runs beside the pre-check, so a queued start can also find a fast verdict or a failure
+ # already saved, and must not revive that run either.
+ if run.status in TERMINAL_STATUSES:
+ activity.logger.info(f"Skipping sandbox for run {run.id} in status {run.status}")
+ return None
- repo_config = run.pull_request.repo_config
- repo = repo_config.repository
+ # Flip to REVIEWING only if a delivery hasn't superseded this run since the early guard above.
+ # A plain save() would blindly overwrite a run that was superseded between the read and the write,
+ # reviving it back to REVIEWING and letting a stale run post its verdict. A conditional update that
+ # refuses to touch a SUPERSEDED row closes that window — 0 rows means it lost the race, so bail
+ # before provisioning the sandbox or fetching a token.
+ updated = (
+ ReviewRun.objects.for_team(input.team_id)
+ .filter(id=run.id)
+ .exclude(status__in=TERMINAL_STATUSES)
+ .update(status=ReviewRunStatus.REVIEWING, updated_at=timezone.now())
+ )
+ if not updated:
+ activity.logger.info(f"Skipping sandbox for run {run.id} (superseded or terminal before REVIEWING)")
+ return None
+ return run
+
+
+def _stored_output(run: ReviewRun) -> dict[str, Any]:
+ """The run's output as the writer holds it now, not the copy this activity loaded."""
+ return (
+ ReviewRun.objects.for_team(run.team_id)
+ .using(router.db_for_write(ReviewRun))
+ .filter(id=run.id)
+ .values_list("output", flat=True)
+ .first()
+ ) or {}
+
+
+def _claim_once(run: ReviewRun, claim: str) -> None:
+ """Record ``claim`` on the run, or raise SandboxPhaseError when an earlier attempt already did.
+
+ 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 or a second paid review.
+ One conditional update writes the claim only where it is absent, so two attempts in the same
+ instant cannot both pass.
+ """
+ stamp = timezone.now().isoformat()
+ claimed = (
+ ReviewRun.objects.for_team(run.team_id)
+ .using(router.db_for_write(ReviewRun))
+ .filter(id=run.id)
+ .exclude(output__has_key=claim)
+ .update(output=_output_merge({claim: stamp}), updated_at=timezone.now())
+ )
+ if not claimed:
+ raise SandboxPhaseError(f"an earlier attempt already recorded {claim} for this run")
+ run.output = {**(run.output or {}), claim: stamp}
+
+
+def _create_review_sandbox(
+ run: ReviewRun, gateway: AIGatewayConfig, token: str, timer: _StepTimer, deadline: float
+) -> SandboxBase:
+ """Provision the review sandbox and fetch the PR head into it.
+
+ Raises SandboxPhaseError from the provision on, which the retry policy excludes. A head fetch
+ that fails tears the new sandbox down first.
+ """
+ config = SandboxConfig(
+ name=f"stamphog-review-{run.id}",
+ template=SandboxTemplate.STAMPHOG_REVIEW,
+ metadata={"review_run_id": str(run.id)},
+ environment_variables=_reviewer_environment(run, gateway),
+ outbound_domain_allowlist=_sandbox_egress_allowlist(gateway.url),
+ )
+ # The steps above cost nothing and keep their own exception type. From here the run makes a
+ # sandbox, so failures raise SandboxPhaseError. The claim stays outside the try below, so the
+ # refusal keeps its own type and a failed write stays retryable.
+ _claim_once(run, "sandbox_started_at")
+ sandbox_class = get_sandbox_class_for_backend(_resolve_sandbox_backend())
+ try:
+ # Raises when the budget is already gone, so an activity with no time left does not pay
+ # for a box the first step would only reject.
+ _step_timeout(deadline, CLONE_STEP_TIMEOUT_SECONDS)
+ with timer.step("sandbox_create"):
+ sandbox = sandbox_class.create(config)
+ except Exception as exc:
+ # Our own infrastructure fails here, so the type is enough: the provider message can
+ # carry the environment it was given.
+ raise SandboxPhaseError(f"the sandbox phase failed with {type(exc).__name__}") from exc
+ try:
+ # The later activities reconnect by this id, and the workflow's teardown reads it.
+ _merge_run_output(run, {"sandbox_id": sandbox.id})
+ # The teardown marks the run before it reads the id, and this reads the mark after writing
+ # the id, so one side always sees the other. A create that outlived its activity, after a
+ # timeout or a cancelled workflow, tears its own sandbox down.
+ if _stored_output(run).get("sandbox_abandoned"):
+ raise RuntimeError("the workflow abandoned this sandbox before it existed")
+ with timer.step("fetch_head"):
+ _clone_pr(
+ sandbox,
+ run.pull_request.repo_config.repository,
+ "",
+ run.head_sha,
+ run.pull_request.pr_number,
+ token,
+ deadline,
+ step="head",
+ )
+ except Exception as exc:
+ _destroy_sandbox_in_background(sandbox, str(run.id))
+ raise SandboxPhaseError(f"the sandbox phase failed with {type(exc).__name__}") from exc
+ return sandbox
+
+
+def _review_merge_base(run: ReviewRun, client: StamphogGitHubClient) -> str:
+ """The merge base the checkout fetches and the review diffs against.
+
+ The context fetch stores the merge base, but it keeps going without one, because familiarity
+ only degrades. The shallow checkout cannot diff without it, so read it again. A failure raises
+ before the sandbox steps, and the activity retries.
+ """
output = run.output or {}
- pr = output.get("pr", {})
- policy_files = output.get("policy_files", {})
+ base_sha = ((output.get("pr") or {}).get("base") or {}).get("sha") or ""
+ return output.get("merge_base_sha") or client.get_merge_base_sha(
+ run.pull_request.repo_config.repository, base_sha, run.head_sha
+ )
+
+def _check_out_review(
+ sandbox: SandboxBase, run: ReviewRun, merge_base_sha: str, token: str, timer: _StepTimer, deadline: float
+) -> None:
+ repo = run.pull_request.repo_config.repository
+ with timer.step("checkout"):
+ _clone_pr(
+ sandbox, repo, merge_base_sha, run.head_sha, run.pull_request.pr_number, token, deadline, step="checkout"
+ )
+ with timer.step("prefetch"):
+ _prefetch_review_blobs(sandbox, merge_base_sha, token, deadline)
+
+
+def _run_reviewer(
+ sandbox: SandboxBase,
+ run: ReviewRun,
+ merge_base_sha: str,
+ gateway_token: str,
+ scrub_tokens: Sequence[str],
+ timer: _StepTimer,
+ deadline: float,
+) -> ExecutionResult:
+ repo = run.pull_request.repo_config.repository
# The trusted source for each policy file is the repo's default branch layered over the
# server-shipped defaults (see _effective_policy_files): policy.yml is a section overlay, the
# guidance file is repo-else-default, steering is repo-else-omitted. The gate policy and the
@@ -913,131 +1098,215 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
# malicious guidance ("approve my PR") in a repo whose default branch lacks the file — the
# PR-head wipe in _review_payload_command stays mandatory, and the fallback content is
# server-owned, never the PR's.
- policy_files = _effective_policy_files(repo, policy_files)
+ policy_files = _effective_policy_files(repo, (run.output or {}).get("policy_files", {}))
+ invocation = _review_invocation(run, merge_base_sha)
- base_sha = (pr.get("base") or {}).get("sha") or ""
+ # The prefetch swallows its own failure, including a timeout that consumed the rest of the
+ # budget. Re-check here, because the archive write below goes through the sandbox filesystem
+ # API and cannot take a deadline: passing one would switch it to an exec-based write, which is a
+ # different mechanism, not a bounded one.
+ _step_timeout(deadline, REVIEWER_TIMEOUT_SECONDS)
+ with timer.step("ship_engine"):
+ _ship_review_payload(sandbox, policy_files, invocation.context_json, deadline)
+ # Through the filesystem API like the payload, so the token never appears in a command line.
+ sandbox.write_file(STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH, gateway_token.encode())
+
+ # GNU date prints epoch milliseconds, so the engine can report how long `uv run` took to reach
+ # its main(). The token file is read and removed before the engine starts, so the only copy the
+ # reviewer holds is its own environment.
+ token_path = shlex.quote(STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH)
+ command = (
+ f'export AI_GATEWAY_API_KEY="$(cat {token_path})" && rm -f {token_path} && '
+ f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && "
+ f"STAMPHOG_LAUNCHED_AT_MS=$(date +%s%3N) {_harden_reviewer_command(invocation.command)}"
+ )
+ with timer.step("reviewer"):
+ result = sandbox.execute(command, timeout_seconds=_step_timeout(deadline, REVIEWER_TIMEOUT_SECONDS))
- # Flip to REVIEWING only if a delivery hasn't superseded this run since the early guard above.
- # A plain save() would blindly overwrite a run that was superseded between the read and the write,
- # reviving it back to REVIEWING and letting a stale run post its verdict. A conditional update that
- # refuses to touch a SUPERSEDED row closes that window — 0 rows means it lost the race, so bail
- # before provisioning the sandbox or fetching a token.
- updated = (
- ReviewRun.objects.for_team(input.team_id)
- .filter(id=run.id)
- .exclude(status=ReviewRunStatus.SUPERSEDED)
- .update(status=ReviewRunStatus.REVIEWING, updated_at=timezone.now())
+ # 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.
+ _merge_run_output(
+ run,
+ {
+ "reviewer_raw": scrub_credentials(result.stdout, *scrub_tokens, gateway_token),
+ "reviewer_exit_code": result.exit_code,
+ "engine_timings_ms": parse_engine_timings(result.stdout),
+ },
)
- if not updated:
- activity.logger.info(f"Skipping sandbox for superseded run {run.id} (superseded before REVIEWING)")
- return {"skipped": "superseded"}
+ 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, *scrub_tokens, gateway_token)[:500]}"
+ )
+ raise RuntimeError(f"reviewer exited with code {result.exit_code}")
+ return result
- client = StamphogGitHubClient(repo_config.installation_id)
+
+def _reconnect_review_sandbox(sandbox_id: str) -> SandboxBase:
+ return get_sandbox_class_for_backend(_resolve_sandbox_backend()).get_by_id(sandbox_id)
+
+
+@asyncify
+def start_review_sandbox(input: StamphogReviewInput) -> dict:
+ """Provision the review sandbox and fetch the PR head, beside the context fetch.
+
+ The head fetch needs only the run row, so it runs while the context loads. The workflow awaits
+ this activity and the ones after it. No activity waits inside for another one, because a waiting
+ activity holds a worker thread that the activity it waits for could need.
+ """
+ deadline = _sandbox_deadline(SANDBOX_START_TIMEOUT)
+ run = _begin_sandbox_phase(input)
+ if run is None:
+ return {"skipped": "terminal"}
+ gateway = _hosted_gateway()
+ client = StamphogGitHubClient(run.pull_request.repo_config.installation_id)
token = client._get_installation_token()
- # The context fetch stores the merge base, but it keeps going without one, because familiarity
- # only degrades. The shallow checkout cannot diff without it, so read it again here. A failure
- # raises before the sandbox exists, and the activity retries.
- merge_base_sha = output.get("merge_base_sha") or client.get_merge_base_sha(repo, base_sha, run.head_sha)
+ timer = _StepTimer()
+ try:
+ sandbox = _create_review_sandbox(run, gateway, token, timer, deadline)
+ finally:
+ _save_step_timings(run, "sandbox_start_timings_ms", timer.timings_ms)
+ return {"sandbox_id": sandbox.id}
- invocation = _review_invocation(run, merge_base_sha)
- sandbox_class = get_sandbox_class_for_backend(_resolve_sandbox_backend())
- environment, gateway = _reviewer_environment(run)
+@asyncify
+def checkout_review_sandbox(input: ReviewSandboxInput) -> dict:
+ deadline = _sandbox_deadline(SANDBOX_CHECKOUT_TIMEOUT)
+ run = _load_run(input)
+ if run.status in TERMINAL_STATUSES:
+ activity.logger.info(f"Skipping the checkout for run {run.id} in status {run.status}")
+ _destroy_sandbox_in_background(_reconnect_review_sandbox(input.sandbox_id), str(run.id))
+ return {"skipped": run.status}
+ client = StamphogGitHubClient(run.pull_request.repo_config.installation_id)
+ token = client._get_installation_token()
+ merge_base_sha = _review_merge_base(run, client)
+ # Outside the wrapped block, so a transient provider lookup error stays retryable.
+ sandbox = _reconnect_review_sandbox(input.sandbox_id)
+ timer = _StepTimer()
+ try:
+ _check_out_review(sandbox, run, merge_base_sha, token, timer, deadline)
+ except Exception as exc:
+ # Give the type only: a failed git step reports its stderr, which can name repository content.
+ raise SandboxPhaseError(f"the sandbox phase failed with {type(exc).__name__}") from exc
+ finally:
+ steps = timer.timings_ms
+ fetch_head_ms = ((run.output or {}).get("sandbox_start_timings_ms") or {}).get("fetch_head")
+ if isinstance(fetch_head_ms, int) and "checkout" in steps:
+ steps["clone"] = fetch_head_ms + steps["checkout"]
+ _save_step_timings(run, "checkout_timings_ms", steps)
+ return {"merge_base_sha": merge_base_sha}
+
+
+@asyncify
+def review_in_sandbox(input: ReviewSandboxInput) -> dict:
+ deadline = _sandbox_deadline(RUN_REVIEW_TIMEOUT)
+ run = _load_run(input)
+ if run.status in TERMINAL_STATUSES:
+ activity.logger.info(f"Skipping the review for run {run.id} in status {run.status}")
+ _destroy_sandbox_in_background(_reconnect_review_sandbox(input.sandbox_id), str(run.id))
+ return {"skipped": run.status}
+ # The checkout ran git with this token. Scrub it too, in case a git step left it in the sandbox.
+ token = StamphogGitHubClient(run.pull_request.repo_config.installation_id)._get_installation_token()
+ # Minted here and not at provision, so the token outlives the review whatever the bot wait took.
+ gateway = _hosted_gateway()
+ gateway_token = _mint_reviewer_scoped_token(gateway, run, _connected_user(run))
+ try:
+ # Before the claim, so a transient provider lookup error stays retryable.
+ sandbox = _reconnect_review_sandbox(input.sandbox_id)
+ _claim_once(run, "reviewer_started_at")
+ timer = _StepTimer()
+ try:
+ result = _run_reviewer(sandbox, run, input.merge_base_sha, gateway_token, [token], timer, deadline)
+ 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.
+ raise SandboxPhaseError(f"the sandbox phase failed with {type(exc).__name__}") from exc
+ finally:
+ # A destroy failure must not mask a completed review, because the verdict still has to be
+ # persisted and posted.
+ with timer.step("destroy_dispatch"):
+ _destroy_sandbox_in_background(sandbox, str(run.id))
+ _save_step_timings(run, "timings_ms", timer.timings_ms)
+ activity.logger.info(f"Sandbox step timings for run {run.id}: {timer.timings_ms}")
+ finally:
+ _release_reviewer_token(gateway, gateway_token)
+
+ activity.logger.info(f"Reviewer completed for run {run.id}")
+ return {"exit_code": result.exit_code}
+
+
+@asyncify
+def destroy_review_sandbox(input: ReviewSandboxInput) -> dict:
+ """Tear down the run's sandbox when no review will use it: a pre-check verdict, or a failed run.
+
+ An empty ``sandbox_id`` means the start returned none. The run can still hold one, because
+ start_review_sandbox records it before its head fetch, and a failed start returns no result.
+ """
+ sandbox_id = input.sandbox_id
+ if not sandbox_id:
+ # A start that returned no id can still be creating the sandbox. Marked before the id read:
+ # _create_review_sandbox holds the other half of this handshake.
+ run = _load_run(input)
+ _merge_run_output(run, {"sandbox_abandoned": True})
+ sandbox_id = _stored_output(run).get("sandbox_id") or ""
+ if not sandbox_id:
+ return {"destroyed": False}
+ try:
+ _reconnect_review_sandbox(sandbox_id).destroy()
+ except SandboxNotFoundError:
+ return {"destroyed": False}
+ return {"destroyed": True}
+
+
+@asyncify
+def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
+ """Provision a sandbox, clone the PR, run the full engine offline, stash its raw output.
+
+ The serial path, for workflow histories from before the sandbox started beside the context fetch.
+ """
+ deadline = _sandbox_deadline(RUN_REVIEW_TIMEOUT)
+ run = _begin_sandbox_phase(input)
+ if run is None:
+ return {"skipped": "terminal"}
+
+ client = StamphogGitHubClient(run.pull_request.repo_config.installation_id)
+ token = client._get_installation_token()
+ merge_base_sha = _review_merge_base(run, client)
+ gateway = _hosted_gateway()
# Per-run credential, not in the worker env — scrub it explicitly wherever sandbox output
# is persisted or raised (llm_env_secrets only covers worker-env values).
- gateway_token = environment["AI_GATEWAY_API_KEY"]
+ gateway_token = _mint_reviewer_scoped_token(gateway, run, _connected_user(run))
# Every path from here releases the token, including a failed claim read or save.
try:
- config = SandboxConfig(
- name=f"stamphog-review-{run.id}",
- template=SandboxTemplate.STAMPHOG_REVIEW,
- metadata={"review_run_id": str(run.id)},
- environment_variables=environment,
- outbound_domain_allowlist=_sandbox_egress_allowlist(environment["AI_GATEWAY_URL"]),
- )
- # 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"])
-
timer = _StepTimer()
- # Sandbox creation draws on the same budget as the steps below it, so a slow provision
- # leaves the clone, the prefetch and the reviewer correspondingly less.
try:
- # Raises when the budget is already gone, so an activity with no time left does not pay
- # for a box the first step would only reject.
- _step_timeout(deadline, CLONE_STEP_TIMEOUT_SECONDS)
- with timer.step("sandbox_create"):
- sandbox = sandbox_class.create(config)
+ sandbox = _create_review_sandbox(run, gateway, token, timer, deadline)
try:
- with timer.step("clone"):
- _clone_pr(sandbox, repo, merge_base_sha, run.head_sha, run.pull_request.pr_number, token, deadline)
- with timer.step("prefetch"):
- _prefetch_review_blobs(sandbox, merge_base_sha, token, deadline)
- # The prefetch swallows its own failure, including a timeout that consumed the rest
- # of the budget. Re-check here, because the archive write below goes through the
- # sandbox filesystem API and cannot take a deadline: passing one would switch it to
- # an exec-based write, which is a different mechanism, not a bounded one.
- _step_timeout(deadline, REVIEWER_TIMEOUT_SECONDS)
- with timer.step("ship_engine"):
- _ship_review_payload(sandbox, policy_files, invocation.context_json, deadline)
-
- # GNU date prints epoch milliseconds, so the engine can report how long `uv run` took to
- # reach its main().
- command = (
- f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && "
- f"STAMPHOG_LAUNCHED_AT_MS=$(date +%s%3N) {_harden_reviewer_command(invocation.command)}"
- )
- with timer.step("reviewer"):
- result = sandbox.execute(command, timeout_seconds=_step_timeout(deadline, REVIEWER_TIMEOUT_SECONDS))
+ _check_out_review(sandbox, run, merge_base_sha, token, timer, deadline)
+ timer.timings_ms["clone"] = timer.timings_ms["fetch_head"] + timer.timings_ms["checkout"]
+ result = _run_reviewer(sandbox, run, merge_base_sha, gateway_token, [token], timer, deadline)
finally:
# A destroy failure must not mask a completed review, because the verdict below still
# has to be persisted and posted.
with timer.step("destroy_dispatch"):
_destroy_sandbox_in_background(sandbox, str(run.id))
- activity.logger.info(f"Sandbox step timings for run {run.id}: {timer.timings_ms}")
-
- # 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,
- "timings_ms": timer.timings_ms,
- "engine_timings_ms": parse_engine_timings(result.stdout),
- }
- run.save(update_fields=["output", "updated_at"])
-
- 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 SandboxPhaseError:
+ raise
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
+ finally:
+ _save_step_timings(run, "timings_ms", timer.timings_ms)
+ activity.logger.info(f"Sandbox step timings for run {run.id}: {timer.timings_ms}")
finally:
_release_reviewer_token(gateway, gateway_token)
@@ -1210,7 +1479,13 @@ def _review_timing_properties(run: ReviewRun, verdict: str, post_verdict_ms: int
"""
output = run.output or {}
pull_request = run.pull_request
- steps = output.get("timings_ms") or {}
+ # The sandbox start and checkout record their steps under their own keys, because they can run
+ # beside the pre-check, which writes timings_ms.
+ steps = {
+ **(output.get("sandbox_start_timings_ms") or {}),
+ **(output.get("checkout_timings_ms") or {}),
+ **(output.get("timings_ms") or {}),
+ }
engine = output.get("engine_timings_ms") or {}
bot_wait = output.get("bot_wait") or {}
properties: dict[str, object] = {
@@ -1248,8 +1523,7 @@ def _capture_review_timings(run: ReviewRun, verdict: str, post_verdict_ms: int)
event="stamphog_review_timings",
properties=_review_timing_properties(run, verdict, post_verdict_ms),
)
- run.output = {**(run.output or {}), "timings_captured": True}
- run.save(update_fields=["output", "updated_at"])
+ _merge_run_output(run, {"timings_captured": True})
except Exception:
activity.logger.exception(f"Failed to capture review timings for run {run.id}")
@@ -1322,7 +1596,7 @@ def post_verdict(input: StamphogReviewInput) -> dict:
# env secrets, the same belt-and-braces the review body gets below.
run.change_summary = scrub_credentials(parsed.change_summary)
if parsed.stamphog_version:
- run.output = {**output, "stamphog_version": parsed.stamphog_version}
+ _merge_run_output(run, {"stamphog_version": parsed.stamphog_version})
update_fields = [
"gate_result",
@@ -1333,9 +1607,6 @@ def post_verdict(input: StamphogReviewInput) -> dict:
"verdict_posted_at",
"updated_at",
]
- if parsed.stamphog_version:
- update_fields.append("output")
-
# Last look before any GitHub write: a same-head re-review delivery (e.g. a trigger-label re-add)
# supersedes this run WITHOUT moving the head, so the head guard above can't catch it — only a
# fresh status read can.
@@ -1407,9 +1678,7 @@ def post_verdict(input: StamphogReviewInput) -> dict:
# One post for every non-approval, keyed off the verdict the run just stored, so the review text
# and the recorded verdict cannot disagree. The approve branch above posted its own APPROVE.
if run.verdict != ReviewVerdict.APPROVED:
- _post_non_approval_review(
- client, repo, run, pull_request, input.team_id, _verdict_body(parsed, run.verdict, relabel_label)
- )
+ _post_non_approval_review(client, repo, run, pull_request, _verdict_body(parsed, run.verdict, relabel_label))
# Keyed off parsed.verdict, not run.verdict: the gate-blocked branch overrides run.verdict to WAIT,
# but both the label-strip and the ReviewHog handoff below treat a gate-blocked refusal the same
@@ -1626,6 +1895,7 @@ def _clone_pr(
pr_number: int,
token: str,
deadline: float,
+ step: Literal["head", "checkout"],
) -> None:
"""Fetch the PR head with its files and the merge base without them, then check out the head.
@@ -1651,6 +1921,9 @@ def _clone_pr(
against a newer pull ref.
The remote stays a clean, tokenless URL. See _git_credential for how the token reaches git.
+
+ ``step`` runs one half: ``head`` needs no merge base, so the sandbox start fetches the head
+ while the context fetch still looks the merge base up, and runs ``checkout`` once it has it.
"""
credential = _git_credential(token)
auth = credential.command
@@ -1669,21 +1942,23 @@ def _clone_pr(
if result.exit_code != 0:
raise RuntimeError(f"{failure_prefix}: {scrub_credentials(result.stderr, token, credential.secret)[:500]}")
- fetch_head = (
- f"rm -rf {repo_dir} && git init --quiet {repo_dir} && cd {repo_dir} && "
- f"git remote add origin {shlex.quote(repo_url)} && "
- f"{auth} fetch --quiet --depth=1 --no-tags origin {shlex.quote(f'pull/{pr_number}/head')} && "
- f'fetched=$(git rev-parse FETCH_HEAD) && if [ "$fetched" != {shlex.quote(head_sha)} ]; then '
- f'echo "the PR head is now $fetched" >&2; exit 1; fi'
- )
- _execute_or_raise(fetch_head, f"Failed to fetch the PR head {head_sha}")
+ if step == "head":
+ fetch_head = (
+ f"rm -rf {repo_dir} && git init --quiet {repo_dir} && cd {repo_dir} && "
+ f"git remote add origin {shlex.quote(repo_url)} && "
+ f"{auth} fetch --quiet --depth=1 --no-tags origin {shlex.quote(f'pull/{pr_number}/head')} && "
+ f'fetched=$(git rev-parse FETCH_HEAD) && if [ "$fetched" != {shlex.quote(head_sha)} ]; then '
+ f'echo "the PR head is now $fetched" >&2; exit 1; fi'
+ )
+ _execute_or_raise(fetch_head, f"Failed to fetch the PR head {head_sha}")
- checkout = (
- f"cd {repo_dir} && "
- f"{auth} fetch --quiet --depth=1 --no-tags --filter=blob:none origin {shlex.quote(merge_base_sha)} && "
- f"GIT_NO_LAZY_FETCH=1 git checkout --quiet --detach {shlex.quote(head_sha)}"
- )
- _execute_or_raise(checkout, f"Failed to check out {head_sha}")
+ if step == "checkout":
+ checkout = (
+ f"cd {repo_dir} && "
+ f"{auth} fetch --quiet --depth=1 --no-tags --filter=blob:none origin {shlex.quote(merge_base_sha)} && "
+ f"GIT_NO_LAZY_FETCH=1 git checkout --quiet --detach {shlex.quote(head_sha)}"
+ )
+ _execute_or_raise(checkout, f"Failed to check out {head_sha}")
def _prefetch_review_blobs(sandbox: SandboxBase, merge_base_sha: str, token: str, deadline: float) -> None:
@@ -1930,7 +2205,7 @@ NON_APPROVAL_REVIEW_ID_KEY = "non_approval_review_id"
def _post_non_approval_review(
- client: StamphogGitHubClient, repo: str, run: ReviewRun, pull_request: PullRequest, team_id: int, body: str
+ client: StamphogGitHubClient, repo: str, run: ReviewRun, pull_request: PullRequest, body: str
) -> None:
"""Record a non-approval as its own COMMENT review, and remember it so a retry does not repeat it.
@@ -1942,8 +2217,7 @@ def _post_non_approval_review(
if (run.output or {}).get(NON_APPROVAL_REVIEW_ID_KEY) is not None:
return
review = client.post_comment_review(repo, pull_request.pr_number, scrub_credentials(body), run.head_sha)
- run.output = {**(run.output or {}), NON_APPROVAL_REVIEW_ID_KEY: _comment_id(review)}
- ReviewRun.objects.for_team(team_id).filter(id=run.id).update(output=run.output, updated_at=timezone.now())
+ _merge_run_output(run, {NON_APPROVAL_REVIEW_ID_KEY: _comment_id(review)})
FAILURE_NOTICE_BODY = (
@@ -1983,7 +2257,7 @@ def _post_failure_notice(client: StamphogGitHubClient, run: ReviewRun, team_id:
return
_post_non_approval_review(
- client, run.pull_request.repo_config.repository, run, run.pull_request, team_id, FAILURE_NOTICE_BODY
+ client, run.pull_request.repo_config.repository, run, run.pull_request, FAILURE_NOTICE_BODY
)
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index 2d5ddff91e7f..f65b1ba0b27b 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -51,6 +51,8 @@ STAMPHOG_SANDBOX_OWNERS_DIR = f"{STAMPHOG_SANDBOX_REPO_DIR}/tools/owners"
STAMPHOG_SANDBOX_CONTEXT_PATH = f"{STAMPHOG_SANDBOX_REPO_DIR}/.stamphog_review_context.json"
# Outside the checkout, so the archive never shows up in the tree the reviewer explores.
STAMPHOG_SANDBOX_PAYLOAD_PATH = "/tmp/stamphog/review-payload.tar.gz"
+# Outside the checkout too. The reviewer command reads the per-run gateway token from it and removes it.
+STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH = "/tmp/stamphog/gateway-token"
# Trusted review-norms prose the engine reads as its reviewer system guidance, and
# the gate policy entrypoint. Both are fetched from the target repo's DEFAULT branch
@@ -74,10 +76,16 @@ FETCH_CONTEXT_TIMEOUT = timedelta(minutes=5)
# Two engine pre-check runs and one short LLM call, each capped at 30 seconds, plus the token mint.
PRE_GATES_TIMEOUT = timedelta(minutes=3)
RUN_REVIEW_TIMEOUT = timedelta(minutes=30)
+# The provision and the PR head fetch, and later the checkout and the blob prefetch. Each runs beside
+# the context fetch, the pre-check or the bot wait, as its own activity, so the waits between them are
+# workflow awaits. Each budget is its step ceilings plus SANDBOX_PHASE_RESERVE_SECONDS.
+SANDBOX_START_TIMEOUT = timedelta(minutes=10)
+SANDBOX_CHECKOUT_TIMEOUT = timedelta(minutes=10)
+SANDBOX_DESTROY_TIMEOUT = timedelta(minutes=2)
# Ceilings for the steps inside the review activity. They add up to more than RUN_REVIEW_TIMEOUT on
# purpose: each one caps a step that should never take that long, while the shared deadline in
-# run_review_in_sandbox caps what the steps can spend between them. Granting each step its own
+# each sandbox activity caps what the steps can spend between them. Granting each step its own
# independent budget was the bug — the clone alone could hold the activity for twice its ceiling.
CLONE_STEP_TIMEOUT_SECONDS = 5 * 60
PREFETCH_DIFF_BLOBS_TIMEOUT_SECONDS = 3 * 60
diff --git a/products/stamphog/backend/temporal/registry.py b/products/stamphog/backend/temporal/registry.py
index 0ca8e76e751c..9c58f9fe4675 100644
--- a/products/stamphog/backend/temporal/registry.py
+++ b/products/stamphog/backend/temporal/registry.py
@@ -7,14 +7,18 @@ stable import target: ``from products.stamphog.backend.temporal.registry import
from __future__ import annotations
from products.stamphog.backend.temporal.activities import (
+ checkout_review_sandbox,
+ destroy_review_sandbox,
dismiss_stale_approvals,
fetch_review_context,
list_in_flight_reviewer_bots,
mark_review_failed,
post_verdict,
refuse_on_pre_gates,
+ review_in_sandbox,
run_review_in_sandbox,
signal_review_started,
+ start_review_sandbox,
)
from products.stamphog.backend.temporal.workflow import StamphogReviewWorkflow
@@ -23,10 +27,14 @@ WORKFLOWS = [StamphogReviewWorkflow]
ACTIVITIES = [
dismiss_stale_approvals,
signal_review_started,
+ start_review_sandbox,
fetch_review_context,
+ checkout_review_sandbox,
refuse_on_pre_gates,
list_in_flight_reviewer_bots,
+ review_in_sandbox,
run_review_in_sandbox,
+ destroy_review_sandbox,
post_verdict,
mark_review_failed,
]
diff --git a/products/stamphog/backend/temporal/workflow.py b/products/stamphog/backend/temporal/workflow.py
index 36639313ccf8..edc0c297eb1c 100644
--- a/products/stamphog/backend/temporal/workflow.py
+++ b/products/stamphog/backend/temporal/workflow.py
@@ -4,8 +4,8 @@ Orchestrates a single PR review: fetch context -> run the engine's gates on the
right away when they alone decide the verdict -> otherwise run the whole engine (gates, tier,
familiarity, LLM review) offline in a sandbox -> post the verdict. Both gate runs are the engine's own
code and surface through the same verdict output. Any unrecoverable error marks the ``ReviewRun``
-FAILED. The workflow only ever moves ``StamphogReviewInput`` (two small fields) between activities;
-all bulky data lives on ``ReviewRun.output`` in Postgres.
+FAILED. The workflow only moves small inputs between activities (the run id, and a sandbox id and
+merge base for the sandbox steps); all bulky data lives on ``ReviewRun.output`` in Postgres.
"""
from __future__ import annotations
@@ -26,7 +26,10 @@ from products.stamphog.backend.temporal.constants import (
POST_VERDICT_TIMEOUT,
PRE_GATES_TIMEOUT,
RUN_REVIEW_TIMEOUT,
+ SANDBOX_CHECKOUT_TIMEOUT,
+ SANDBOX_DESTROY_TIMEOUT,
SANDBOX_RETRY_POLICY,
+ SANDBOX_START_TIMEOUT,
STAMPHOG_BOT_REVIEW_MAX_POLLS,
STAMPHOG_BOT_REVIEW_POLL_SECONDS,
)
@@ -34,15 +37,20 @@ from products.stamphog.backend.temporal.constants import (
with temporalio.workflow.unsafe.imports_passed_through():
from products.stamphog.backend.temporal.activities import (
MarkReviewFailedInput,
+ ReviewSandboxInput,
StamphogReviewInput,
+ checkout_review_sandbox,
+ destroy_review_sandbox,
dismiss_stale_approvals,
fetch_review_context,
list_in_flight_reviewer_bots,
mark_review_failed,
post_verdict,
refuse_on_pre_gates,
+ review_in_sandbox,
run_review_in_sandbox,
signal_review_started,
+ start_review_sandbox,
)
@@ -52,6 +60,8 @@ class StamphogReviewWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, input: StamphogReviewInput) -> dict:
+ sandbox_start: asyncio.Future[dict] | None = None
+ sandbox_checkout: asyncio.Future[ReviewSandboxInput | None] | None = None
try:
# Dismiss any approval from an earlier head FIRST — before context fetch, not just before
# the re-review. Fail-closed ordering: if any later step exhausts retries and the run is
@@ -76,6 +86,21 @@ class StamphogReviewWorkflow(PostHogWorkflow):
retry_policy=ACTIVITY_RETRY_POLICY,
)
+ # The sandbox and the PR head fetch need nothing the next steps produce, so they start now
+ # and run beside the context fetch. The checkout starts once the context holds the merge
+ # base, and runs beside the pre-check and the bot wait. The workflow does every wait
+ # between them: an activity that waited for another activity would hold a worker thread
+ # the other one could need. Gated for replay like the eyes reaction above.
+ if workflow.patched("stamphog-overlap-sandbox"):
+ sandbox_start = asyncio.ensure_future(
+ workflow.execute_activity(
+ start_review_sandbox,
+ input,
+ start_to_close_timeout=SANDBOX_START_TIMEOUT,
+ retry_policy=SANDBOX_RETRY_POLICY,
+ )
+ )
+
await workflow.execute_activity(
fetch_review_context,
input,
@@ -83,6 +108,9 @@ class StamphogReviewWorkflow(PostHogWorkflow):
retry_policy=ACTIVITY_RETRY_POLICY,
)
+ if sandbox_start is not None:
+ sandbox_checkout = asyncio.ensure_future(self._check_out_sandbox(input, sandbox_start))
+
# A PR that fails a deterministic gate is refused whatever the reviewer says, so the
# engine's own gates run here first on the stored context. A final gate verdict (a deny,
# or the WAIT for a pending migration check) is persisted in the sandbox's output shape,
@@ -104,7 +132,7 @@ class StamphogReviewWorkflow(PostHogWorkflow):
workflow.logger.warning(f"stamphog pre-gates failed for run {input.review_run_id}")
if not refused_on_pre_gates:
- # Wait out in-flight reviewer bots (fresh trusted-bot 👀) before provisioning: the
+ # Wait out in-flight reviewer bots (fresh trusted-bot 👀) before the review: the
# sandbox holds no token to poll GitHub with, so the Action's wait-and-poll lives here
# as durable timers. Each poll refreshes the stored reactions snapshot; if the budget
# expires with a bot still in flight, the run proceeds and the engine sees the fresh 👀
@@ -120,12 +148,20 @@ class StamphogReviewWorkflow(PostHogWorkflow):
break
await asyncio.sleep(STAMPHOG_BOT_REVIEW_POLL_SECONDS)
- await workflow.execute_activity(
- run_review_in_sandbox,
- input,
- start_to_close_timeout=RUN_REVIEW_TIMEOUT,
- retry_policy=SANDBOX_RETRY_POLICY,
- )
+ if sandbox_checkout is None:
+ await workflow.execute_activity(
+ run_review_in_sandbox,
+ input,
+ start_to_close_timeout=RUN_REVIEW_TIMEOUT,
+ retry_policy=SANDBOX_RETRY_POLICY,
+ )
+ elif (checked_out := await sandbox_checkout) is not None:
+ await workflow.execute_activity(
+ review_in_sandbox,
+ checked_out,
+ start_to_close_timeout=RUN_REVIEW_TIMEOUT,
+ retry_policy=SANDBOX_RETRY_POLICY,
+ )
result = await workflow.execute_activity(
post_verdict,
@@ -133,20 +169,87 @@ class StamphogReviewWorkflow(PostHogWorkflow):
start_to_close_timeout=POST_VERDICT_TIMEOUT,
retry_policy=ACTIVITY_RETRY_POLICY,
)
+ if refused_on_pre_gates and sandbox_start is not None:
+ # After the verdict, so a pre-check verdict posts without waiting for the clone.
+ await self._discard_sandbox(input, sandbox_start, sandbox_checkout)
return {"status": "completed", "verdict": result["verdict"]}
+ except asyncio.CancelledError:
+ # A cancelled workflow still owns its sandbox, and CancelledError is not an Exception.
+ if sandbox_start is not None:
+ await self._discard_sandbox(input, sandbox_start, sandbox_checkout)
+ raise
except Exception as e:
# Log the full error to the worker before marking the run failed: mark_review_failed
# persists only the first line (raw exception text can embed repo file content, and run.error
# is exposed to stamphog:read), so the worker log is where full detail is kept.
workflow.logger.error(f"stamphog_review_workflow_failed for run {input.review_run_id}: {e}")
+ try:
+ await workflow.execute_activity(
+ mark_review_failed,
+ MarkReviewFailedInput(
+ review_run_id=input.review_run_id,
+ team_id=input.team_id,
+ error=describe_failure(e),
+ ),
+ start_to_close_timeout=MARK_FAILED_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+ finally:
+ if sandbox_start is not None:
+ await self._discard_sandbox(input, sandbox_start, sandbox_checkout)
+ raise
+
+ async def _check_out_sandbox(
+ self, input: StamphogReviewInput, sandbox_start: asyncio.Future[dict]
+ ) -> ReviewSandboxInput | None:
+ """Check out the PR in the started sandbox. None when a superseded run skipped the start or the checkout."""
+ started = await sandbox_start
+ sandbox_id = started.get("sandbox_id")
+ if not sandbox_id:
+ return None
+ sandbox = ReviewSandboxInput(review_run_id=input.review_run_id, team_id=input.team_id, sandbox_id=sandbox_id)
+ checkout = await workflow.execute_activity(
+ checkout_review_sandbox,
+ sandbox,
+ start_to_close_timeout=SANDBOX_CHECKOUT_TIMEOUT,
+ retry_policy=SANDBOX_RETRY_POLICY,
+ )
+ if checkout.get("skipped"):
+ return None
+ return ReviewSandboxInput(
+ review_run_id=input.review_run_id,
+ team_id=input.team_id,
+ sandbox_id=sandbox_id,
+ merge_base_sha=checkout["merge_base_sha"],
+ )
+
+ async def _discard_sandbox(
+ self,
+ input: StamphogReviewInput,
+ sandbox_start: asyncio.Future[dict],
+ sandbox_checkout: asyncio.Future[ReviewSandboxInput | None] | None,
+ ) -> None:
+ """Tear down a sandbox no review will use. Never raises: the run already has its outcome.
+
+ Waits for the start and the checkout first, so the teardown finds the sandbox they made
+ rather than racing a provision that is still in flight.
+ """
+ sandbox_id = ""
+ try:
+ sandbox_id = (await sandbox_start).get("sandbox_id") or ""
+ except (Exception, asyncio.CancelledError):
+ pass
+ if sandbox_checkout is not None:
+ try:
+ await sandbox_checkout
+ except (Exception, asyncio.CancelledError):
+ pass
+ try:
await workflow.execute_activity(
- mark_review_failed,
- MarkReviewFailedInput(
- review_run_id=input.review_run_id,
- team_id=input.team_id,
- error=describe_failure(e),
- ),
- start_to_close_timeout=MARK_FAILED_TIMEOUT,
+ destroy_review_sandbox,
+ ReviewSandboxInput(review_run_id=input.review_run_id, team_id=input.team_id, sandbox_id=sandbox_id),
+ start_to_close_timeout=SANDBOX_DESTROY_TIMEOUT,
retry_policy=ACTIVITY_RETRY_POLICY,
)
- raise
+ except ActivityError:
+ workflow.logger.warning(f"stamphog could not tear down the sandbox for run {input.review_run_id}")
diff --git a/products/stamphog/backend/tests/conftest.py b/products/stamphog/backend/tests/conftest.py
index b3fdf01f43d1..a6663333841f 100644
--- a/products/stamphog/backend/tests/conftest.py
+++ b/products/stamphog/backend/tests/conftest.py
@@ -18,15 +18,19 @@ from posthog.temporal.common.errors import describe_failure
from products.stamphog.backend.temporal.activities import (
MarkReviewFailedInput,
+ ReviewSandboxInput,
StamphogReviewInput,
+ checkout_review_sandbox,
+ destroy_review_sandbox,
dismiss_stale_approvals,
fetch_review_context,
list_in_flight_reviewer_bots,
mark_review_failed,
post_verdict,
refuse_on_pre_gates,
- run_review_in_sandbox,
+ review_in_sandbox,
signal_review_started,
+ start_review_sandbox,
)
from products.stamphog.backend.tests import fakes
@@ -120,20 +124,54 @@ def _run_activity(activity_fn: Any, arg: Any) -> Any:
return activity_fn.__wrapped__(arg)
+def _inline_check_out(inp: StamphogReviewInput) -> ReviewSandboxInput | None:
+ """The workflow's _check_out_sandbox: start the sandbox, then check the PR out in it."""
+ started = _run_activity(start_review_sandbox, inp)
+ if not started.get("sandbox_id"):
+ return None
+ sandbox_id = started["sandbox_id"]
+ checkout = _run_activity(
+ checkout_review_sandbox,
+ ReviewSandboxInput(review_run_id=inp.review_run_id, team_id=inp.team_id, sandbox_id=sandbox_id),
+ )
+ if checkout.get("skipped"):
+ return None
+ return ReviewSandboxInput(
+ review_run_id=inp.review_run_id,
+ team_id=inp.team_id,
+ sandbox_id=sandbox_id,
+ merge_base_sha=checkout["merge_base_sha"],
+ )
+
+
+def _discard_input(inp: StamphogReviewInput, checked_out: ReviewSandboxInput | None) -> ReviewSandboxInput:
+ """The workflow's teardown input: the started sandbox's id, or empty to read the stored one."""
+ sandbox_id = checked_out.sandbox_id if checked_out is not None else ""
+ return ReviewSandboxInput(review_run_id=inp.review_run_id, team_id=inp.team_id, sandbox_id=sandbox_id)
+
+
def _inline_review_workflow(review_run_id: str, team_id: int) -> None:
"""Stand in for the Temporal client by driving the real activities in order.
Mirrors StamphogReviewWorkflow: dismiss stale approvals FIRST (fail-closed — even a context-fetch
failure must not leave an earlier head's approval standing), signal the review has started (the
- "review in flight" 👀), then fetch context, refuse on the pre-gates or else run in the (faked)
+ "review in flight" 👀), then fetch context, refuse on the pre-gates or else review in the (faked)
sandbox, post the verdict; on any error mark the run failed, exactly like the workflow's failure
- path.
+ path. The workflow runs the sandbox start and checkout beside the context fetch and the pre-check.
+ Here they run in order after the context fetch, and a failure surfaces where the workflow awaits
+ them: at the review, or never, when a pre-check verdict discards the sandbox.
"""
inp = StamphogReviewInput(review_run_id=review_run_id, team_id=team_id)
+ checked_out: ReviewSandboxInput | None = None
try:
_run_activity(dismiss_stale_approvals, inp)
_run_activity(signal_review_started, inp)
_run_activity(fetch_review_context, inp)
+ checkout_error: Exception | None = None
+ try:
+ checked_out = _inline_check_out(inp)
+ except Exception as e: # noqa: BLE001 — the workflow sees it only when it awaits the checkout
+ checkout_error = e
try:
refused = _run_activity(refuse_on_pre_gates, inp)["refused"]
except Exception: # noqa: BLE001 — the workflow falls through when the pre-gates activity fails
@@ -142,13 +180,21 @@ def _inline_review_workflow(review_run_id: str, team_id: int) -> None:
# One bot-wait poll, no sleeping: mirrors the workflow's loop semantics (refresh the
# reactions snapshot, then proceed) without its durable timers.
_run_activity(list_in_flight_reviewer_bots, inp)
- _run_activity(run_review_in_sandbox, inp)
+ if checkout_error is not None:
+ raise checkout_error
+ if checked_out is not None:
+ _run_activity(review_in_sandbox, checked_out)
_run_activity(post_verdict, inp)
+ if refused:
+ _run_activity(destroy_review_sandbox, _discard_input(inp, checked_out))
except Exception as e: # noqa: BLE001 — mirror the workflow's failure path
- _run_activity(
- mark_review_failed,
- MarkReviewFailedInput(review_run_id, team_id, describe_failure(e)),
- )
+ try:
+ _run_activity(
+ mark_review_failed,
+ MarkReviewFailedInput(review_run_id, team_id, describe_failure(e)),
+ )
+ finally:
+ _run_activity(destroy_review_sandbox, _discard_input(inp, checked_out))
@dataclass
diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.py
index fb773bfd10c5..081ae74e84fc 100644
--- a/products/stamphog/backend/tests/fakes.py
+++ b/products/stamphog/backend/tests/fakes.py
@@ -28,6 +28,7 @@ from typing import Any
from slack_sdk.errors import SlackApiError
from products.stamphog.backend.temporal.constants import STAMPHOG_SANDBOX_PAYLOAD_PATH, STAMPHOG_SANDBOX_REPO_DIR
+from products.tasks.backend.facade.sandbox import SandboxNotFoundError
# --- Webhook payload + signing (mirrors what GitHub sends) ---
@@ -640,18 +641,40 @@ def make_fake_sandbox_class(engine_output: str, write_sink: list[tuple[str, byte
created_configs: list[Any] = []
# Every command passed to execute(), so a test can assert what ran in the sandbox.
executed_commands: list[str] = []
+ # A test can set this to make the reviewer command fail (sandbox-phase failure coverage).
+ reviewer_exit_code: int = 0
+
+ # Every created sandbox by id, so get_by_id hands a later activity the same instance.
+ instances: dict[str, _FakeSandbox] = {}
+
+ def __init__(self, sandbox_id: str) -> None:
+ self.id = sandbox_id
@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()
+ sandbox = cls(f"sb-fake-{len(cls.created_configs)}")
+ cls.instances[sandbox.id] = sandbox
+ return sandbox
+
+ @classmethod
+ def get_by_id(cls, sandbox_id: str) -> _FakeSandbox:
+ if sandbox_id not in cls.instances:
+ raise SandboxNotFoundError(
+ f"no fake sandbox {sandbox_id}",
+ {"sandbox_id": sandbox_id},
+ cause=LookupError(sandbox_id),
+ capture=False,
+ )
+ return cls.instances[sandbox_id]
def execute(self, command: str, timeout_seconds: int | None = None) -> FakeExecResult:
type(self).executed_commands.append(command)
- stdout = engine_output if "review_local.py" in command else ""
- return FakeExecResult(stdout=stdout, stderr="", exit_code=0)
+ if "review_local.py" not in command:
+ return FakeExecResult(stdout="", stderr="", exit_code=0)
+ return FakeExecResult(stdout=engine_output, stderr="", exit_code=self.reviewer_exit_code)
def write_file(self, path: str, payload: bytes) -> FakeExecResult:
if write_sink is not None and path == STAMPHOG_SANDBOX_PAYLOAD_PATH:
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 22597793c834..497b1461abf1 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -41,18 +41,22 @@ from products.stamphog.backend.tasks.tasks import process_inbox_pr_review
from products.stamphog.backend.temporal import activities
from products.stamphog.backend.temporal.activities import (
MarkReviewFailedInput,
+ ReviewSandboxInput,
StamphogReviewInput,
+ destroy_review_sandbox,
dismiss_stale_approvals,
fetch_review_context,
list_in_flight_reviewer_bots,
mark_review_failed,
post_verdict,
run_review_in_sandbox,
+ start_review_sandbox,
)
from products.stamphog.backend.temporal.constants import (
NETWORK_RESTRICTED_AGENT_ENV,
SANDBOX_RETRY_POLICY,
STAMPHOG_SANDBOX_CONTEXT_PATH,
+ STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH,
STAMPHOG_SANDBOX_REPO_DIR,
SandboxPhaseError,
)
@@ -364,7 +368,7 @@ _LIFTING_FOLDER_FILE = "---\nstamphog:\n size_gate:\n max_lines: 1000\n---\n
],
)
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
-def test_a_final_gate_verdict_is_posted_without_a_sandbox(
+def test_a_final_gate_verdict_is_posted_without_a_sandbox_review(
team,
stamphog_chain: StamphogChain,
files: list[dict],
@@ -400,14 +404,16 @@ def test_a_final_gate_verdict_is_posted_without_a_sandbox(
run = ReviewRun.objects.for_team(team.id).filter(pull_request=pull_request).latest("created_at")
assert run.output["pregate_outcome"] == expect_pregate_outcome
if expect_in_body is None:
- assert stamphog_chain.sandbox_class.created_configs != []
+ assert any("review_local.py" in command for command in stamphog_chain.sandbox_class.executed_commands)
assert "fast_path" not in run.output
return
- assert stamphog_chain.sandbox_class.created_configs == []
+ _assert_no_review_ran(stamphog_chain)
assert run.status == ReviewRunStatus.GATED
assert run.output["fast_path"] is True
+ # The pre-check and the sandbox start each time their own steps, and neither write drops the other.
assert "pregate" in run.output["timings_ms"]
+ assert {"sandbox_create", "fetch_head"} <= set(run.output["sandbox_start_timings_ms"])
# The fast path has no checkout, so the commit trailers come from the server's messages alone.
assert json.loads(run.output["reviewer_raw"])["provenance"]["task_ids"] == ["t-1"]
refusals = [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "comment_review"]
@@ -509,8 +515,10 @@ def test_a_second_attempt_never_provisions_a_second_sandbox(team, stamphog_chain
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.
+ # otherwise provision successfully and run the reviewer again. A real retry comes before the
+ # workflow marks the run failed, so the run is still reviewing when it starts.
stamphog_chain.sandbox_class.create_error = None
+ ReviewRun.objects.for_team(team.id).filter(id=run.id).update(status=ReviewRunStatus.REVIEWING)
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
@@ -802,6 +810,13 @@ def _mint_response(
return response
+def _assert_no_review_ran(stamphog_chain: StamphogChain) -> None:
+ # The sandbox starts beside the context fetch, so it can exist. The reviewer must not have run,
+ # and the workflow must have torn the unused sandbox down.
+ assert not any("review_local.py" in command for command in stamphog_chain.sandbox_class.executed_commands)
+ assert stamphog_chain.sandbox_class.destroy_returned
+
+
def _register_review(stamphog_chain: StamphogChain, number: int, head_sha: str) -> dict:
recorder = stamphog_chain.recorder
recorder.register_pr(REPO, number, _pr_object(number, "devex-dev", head_sha), _pr_files())
@@ -831,7 +846,10 @@ def test_sandbox_gets_a_scoped_gateway_token_when_the_go_gateway_is_configured(
config = stamphog_chain.sandbox_class.created_configs[0]
env = config.environment_variables
assert env["AI_GATEWAY_URL"] == "https://ai-gateway.test/v1"
- assert env["AI_GATEWAY_API_KEY"] == "phe_run"
+ # The phe_ is minted after the sandbox exists. It arrives as a file the reviewer command reads,
+ # so it is in no creation env and no command line.
+ assert (STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH, b"phe_run") in stamphog_chain.sandbox_writes
+ assert not any("phe_run" in command for command in stamphog_chain.sandbox_class.executed_commands)
# Nothing long-lived crosses into the sandbox: not the worker's phs_, not an Anthropic key, and
# no key outside the documented set (a widened passthrough goes red here).
assert "phs_stamphog_mint" not in env.values()
@@ -839,7 +857,6 @@ def test_sandbox_gets_a_scoped_gateway_token_when_the_go_gateway_is_configured(
assert set(env) <= {
"STAMPHOG_REPO_DIR",
"AI_GATEWAY_URL",
- "AI_GATEWAY_API_KEY",
"POSTHOG_API_KEY",
"POSTHOG_HOST",
"STAMPHOG_EXTRA_PROPERTIES",
@@ -889,7 +906,7 @@ def test_hosted_review_fails_closed_when_the_scoped_token_mint_fails(team, stamp
assert "gateway" in (run.error or "").lower()
assert "HTTP 503" in (run.error or "")
assert mint.call_count == activities._MINT_ATTEMPTS
- assert not stamphog_chain.sandbox_class.created_configs
+ _assert_no_review_ran(stamphog_chain)
assert not (run.error or "").startswith("SandboxPhaseError")
@@ -918,7 +935,7 @@ def test_scoped_token_mint_waits_out_a_rate_limit_and_obeys_retry_after(team, st
run = ReviewRun.objects.for_team(team.id).latest("created_at")
assert run.status == ReviewRunStatus.COMPLETED
- assert stamphog_chain.sandbox_class.created_configs[0].environment_variables["AI_GATEWAY_API_KEY"] == "phe_run"
+ assert (STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH, b"phe_run") in stamphog_chain.sandbox_writes
# The header wins the first wait; the second grows on its own, jittered but bounded.
assert sleeps[0] == 7.0
assert 2.0 <= sleeps[1] <= 2.5
@@ -941,7 +958,7 @@ def test_scoped_token_mint_does_not_retry_a_credential_rejection(team, stamphog_
assert "HTTP 403" in (run.error or "")
assert "only a standard credential" in (run.error or "")
assert mint.call_count == 1
- assert not stamphog_chain.sandbox_class.created_configs
+ _assert_no_review_ran(stamphog_chain)
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
@@ -1876,9 +1893,9 @@ def test_superseded_refusal_does_not_hand_off_to_reviewhog(team, stamphog_chain:
# the run is REVIEWING at load.
original_post_review = activities._post_non_approval_review
- def _supersede_then_post(client, repo, posting_run, pr, team_id, body) -> None:
+ def _supersede_then_post(client, repo, posting_run, pr, body) -> None:
ReviewRun.objects.for_team(team.id).filter(id=run.id).update(status=ReviewRunStatus.SUPERSEDED)
- original_post_review(client, repo, posting_run, pr, team_id, body)
+ original_post_review(client, repo, posting_run, pr, body)
with patch.object(activities, "_post_non_approval_review", side_effect=_supersede_then_post):
result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
@@ -2502,8 +2519,7 @@ def test_mint_pins_allowed_models_when_configured(team, stamphog_chain: Stamphog
# Empty entries (a trailing comma in the env value) never reach the gateway, which would 400.
assert mint.call_args_list[0].kwargs["json"]["allowed_models"] == ["claude-sonnet-5-5", "claude-haiku-4-5"]
- env = stamphog_chain.sandbox_class.created_configs[0].environment_variables
- assert env["AI_GATEWAY_API_KEY"] == "phe_run"
+ assert (STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH, b"phe_run") in stamphog_chain.sandbox_writes
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
@@ -2521,8 +2537,7 @@ def test_mint_omits_allowed_models_by_default(team, stamphog_chain: StamphogChai
assert "allowed_models" not in mint.call_args_list[0].kwargs["json"]
# No pin was asked for, so a missing echo is not a dropped pin and the review runs.
- env = stamphog_chain.sandbox_class.created_configs[0].environment_variables
- assert env["AI_GATEWAY_API_KEY"] == "phe_run"
+ assert (STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH, b"phe_run") in stamphog_chain.sandbox_writes
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
@@ -2545,7 +2560,7 @@ def test_mint_fails_closed_when_the_gateway_ignores_the_model_pin(team, stamphog
run = ReviewRun.objects.for_team(team.id).latest("created_at")
assert run.status == ReviewRunStatus.FAILED
assert "model pin" in (run.error or "")
- assert stamphog_chain.sandbox_class.created_configs == []
+ _assert_no_review_ran(stamphog_chain)
_, revoke_call = mint.call_args_list
assert revoke_call.args == ("https://ai-gateway.test/v1/tokens/revoke",)
assert revoke_call.kwargs["json"] == {"token": "phe_run"}
@@ -2577,8 +2592,7 @@ def test_mint_retries_a_network_error_and_records_the_outcome(team, stamphog_cha
):
stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
- env = stamphog_chain.sandbox_class.created_configs[0].environment_variables
- assert env["AI_GATEWAY_API_KEY"] == "phe_run"
+ assert (STAMPHOG_SANDBOX_GATEWAY_TOKEN_PATH, b"phe_run") in stamphog_chain.sandbox_writes
assert [call.args[0] for call in mint.call_args_list] == [
"https://ai-gateway.test/v1/tokens",
"https://ai-gateway.test/v1/tokens",
@@ -2598,12 +2612,12 @@ def test_product_tag_matches_the_engine_blob() -> None:
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_scoped_token_is_revoked_when_the_sandbox_phase_fails(team, stamphog_chain: StamphogChain) -> None:
- # The revoke exists for the runs that end badly: a sandbox that cannot be provisioned still had
- # a live token minted for it, and the token dies with the attempt.
+ # The revoke exists for the runs that end badly: a review whose sandbox phase fails still had a
+ # live token minted for it, and the token dies with the attempt.
_repo_config(team.id)
event = _register_review(stamphog_chain, 123, "sha123a")
broken_sandbox = fakes.make_fake_sandbox_class(fakes.approved_engine_output())
- broken_sandbox.create_error = RuntimeError("modal is down")
+ broken_sandbox.reviewer_exit_code = 1
mint = MagicMock(side_effect=[_mint_response(201, {"token": "phe_run"}), _mint_response(200, {"revoked": True})])
with (
@@ -2665,3 +2679,95 @@ def test_a_key_with_the_legacy_url_fails_before_the_mint(team, stamphog_chain: S
assert "legacy stamphog route" in (run.error or "")
mint.assert_not_called()
assert not stamphog_chain.sandbox_class.created_configs
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_overlapping_activities_keep_each_others_output_keys(team, stamphog_chain: StamphogChain) -> None:
+ # The sandbox activity runs beside the context fetch, the pre-check and the bot polls. A write
+ # from a copy loaded before another activity's write must not drop that activity's keys, such as
+ # the sandbox claim that stops a retry from paying for a second sandbox.
+ repo_config = _repo_config(team.id)
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=130, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha="sha130", status=ReviewRunStatus.REVIEWING
+ )
+ stale_copy = ReviewRun.objects.for_team(team.id).get(id=run.id)
+
+ activities._merge_run_output(run, {"sandbox_started_at": "2026-09-25T10:00:00+00:00"})
+ activities._merge_run_output(stale_copy, {"pr_reactions": []})
+
+ stored = ReviewRun.objects.for_team(team.id).get(id=run.id).output
+ assert stored == {"sandbox_started_at": "2026-09-25T10:00:00+00:00", "pr_reactions": []}
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_post_verdict_keeps_output_keys_written_while_it_runs(team, stamphog_chain: StamphogChain) -> None:
+ # A fast verdict posts while the sandbox start can still be writing sandbox_id. The teardown reads
+ # that id, so a post_verdict save from its earlier copy would leak the sandbox.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 131, "sha131a")
+ record_write = stamphog_chain.recorder._record_write
+
+ def record_and_race(kind: str, repo: str, number: int, body: dict | None) -> fakes.FakeResponse:
+ if kind == "approve_review":
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ activities._merge_run_output(run, {"sandbox_id": "sb-late"})
+ return record_write(kind, repo, number, body)
+
+ with patch.object(stamphog_chain.recorder, "_record_write", side_effect=record_and_race):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.COMPLETED
+ assert run.output["sandbox_id"] == "sb-late"
+ assert run.output["timings_captured"] is True
+
+
+ "status", [ReviewRunStatus.GATED, ReviewRunStatus.FAILED, ReviewRunStatus.COMPLETED, ReviewRunStatus.SUPERSEDED]
+)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_late_sandbox_start_leaves_a_finished_run_alone(
+ team, stamphog_chain: StamphogChain, status: ReviewRunStatus
+) -> None:
+ # The start runs beside the pre-check, so a queued start can begin after a fast verdict or a
+ # failure is saved. Flipping that run back to REVIEWING would leave it non-terminal for good.
+ repo_config = _repo_config(team.id)
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=132, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha="sha132", status=status
+ )
+
+ result = _run_activity(start_review_sandbox, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ assert result == {"skipped": "terminal"}
+ assert ReviewRun.objects.for_team(team.id).get(id=run.id).status == status
+ assert not stamphog_chain.sandbox_class.created_configs
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_sandbox_created_after_its_teardown_tears_itself_down(team, stamphog_chain: StamphogChain) -> None:
+ # A start that outlives its activity timeout, or a cancelled workflow, can finish the create after
+ # the workflow's teardown found no sandbox id. The late sandbox must not run until its TTL.
+ repo_config = _repo_config(team.id)
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=133, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha="sha133", status=ReviewRunStatus.REVIEWING
+ )
+ inp = ReviewSandboxInput(review_run_id=str(run.id), team_id=team.id, sandbox_id="")
+
+ assert _run_activity(destroy_review_sandbox, inp) == {"destroyed": False}
+ with (
+ patch.object(activities, "_destroy_sandbox_in_background", lambda sandbox, run_id: sandbox.destroy()),
+ pytest.raises(SandboxPhaseError),
+ ):
+ _run_activity(start_review_sandbox, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ assert len(stamphog_chain.sandbox_class.created_configs) == 1
+ assert stamphog_chain.sandbox_class.destroy_returned
diff --git a/products/stamphog/backend/tests/test_policy_defaults.py b/products/stamphog/backend/tests/test_policy_defaults.py
index e279eeb75ff9..ed66c1f75f04 100644
--- a/products/stamphog/backend/tests/test_policy_defaults.py
+++ b/products/stamphog/backend/tests/test_policy_defaults.py
@@ -131,7 +131,8 @@ def test_clone_and_prefetch_carry_the_credential_on_every_github_fetch() -> None
deadline = time.monotonic() + 600
sandbox = _RecordingSandbox()
- _clone_pr(sandbox, "acme/widgets", "mergebase", "headsha", 7, "tok", deadline) # type: ignore[arg-type]
+ for step in ("head", "checkout"):
+ _clone_pr(sandbox, "acme/widgets", "mergebase", "headsha", 7, "tok", deadline, step=step) # type: ignore[arg-type]
_prefetch_review_blobs(sandbox, "mergebase", "tok", deadline) # type: ignore[arg-type]
# A fetch without the header is anonymous, which a private repository refuses. The token rides
@@ -216,10 +217,11 @@ def test_shallow_clone_holds_every_object_the_pr_diff_reads(
if head_moved:
# The pull ref now names a newer commit than the one this run was queued for.
with pytest.raises(RuntimeError, match="the PR head is now"):
- _clone_pr(sandbox, "acme/widgets", merge_base, base_tip, 7, "tok", deadline) # type: ignore[arg-type]
+ _clone_pr(sandbox, "acme/widgets", "", base_tip, 7, "tok", deadline, step="head") # type: ignore[arg-type]
return
- _clone_pr(sandbox, "acme/widgets", merge_base, head, 7, "tok", deadline) # type: ignore[arg-type]
+ for step in ("head", "checkout"):
+ _clone_pr(sandbox, "acme/widgets", merge_base, head, 7, "tok", deadline, step=step) # type: ignore[arg-type]
_prefetch_review_blobs(sandbox, merge_base, "tok", deadline) # type: ignore[arg-type]
assert _git(target, "rev-parse", "HEAD") == head