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): clone the review sandbox without blobs (#100317)

Julian Bez26766da85014
diff --git a/package.json b/package.json
index c363f4be1595..1e0bc1403338 100644
--- a/package.json
+++ b/package.json
@@ -101,7 +101,7 @@
"products/desktop/**/*.{js,mjs,ts,tsx,json,jsonc,css}": "pnpm --dir products/desktop exec biome check --write --no-errors-on-unmatched --files-ignore-unknown=true",
"nodejs/**/*.{js,jsx,mjs,mts,ts,tsx}": "bin/hogli format:nodejs",
"funnel-udf/**/*.rs": "bin/hogli format:rust",
- "!(posthog/hogql/grammar/*|posthog/personhog_client/proto/generated/*|products/*/skills/*/scripts/*)*.{py,pyi}": [
+ "!(posthog/hogql/grammar/*|posthog/personhog_client/proto/generated/*|products/*/skills/*/scripts/*|products/stamphog/packages/*/*)*.{py,pyi}": [
"bin/hogli lint:python:fix",
"bin/hogli format:python",
"uv run --no-sync ty check"
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index 27fbe9176fad..cf58d804dea9 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -24,7 +24,8 @@ import shlex
import base64
import random
from collections.abc import Sequence
-from dataclasses import dataclass
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
from pathlib import Path
from urllib.parse import urlparse
@@ -38,6 +39,7 @@ import requests
from prometheus_client import Counter
from temporalio import activity
+from posthog.dataclasses import frozen
from posthog.llm.gateway_client import AIGatewayConfig, resolve_ai_gateway_config
from posthog.models import OAuthAccessToken, User
from posthog.ph_client import ph_scoped_capture
@@ -63,6 +65,11 @@ from products.stamphog.backend.logic.reviewer import (
)
from products.stamphog.backend.models import PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfig
from products.stamphog.backend.temporal.constants import (
+ CLONE_STEP_TIMEOUT_SECONDS,
+ PREFETCH_BLAME_TIMEOUT_SECONDS,
+ REVIEWER_TIMEOUT_SECONDS,
+ RUN_REVIEW_TIMEOUT,
+ SANDBOX_PHASE_RESERVE_SECONDS,
STAMPHOG_BOT_EYES_MAX_AGE_SECONDS,
STAMPHOG_OPTIONAL_POLICY_PATHS,
STAMPHOG_POLICY_ENTRYPOINT,
@@ -539,10 +546,46 @@ 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.
+
+ Temporal starts RUN_REVIEW_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
+ try:
+ elapsed = (datetime.now(UTC) - activity.info().started_time).total_seconds()
+ except Exception:
+ elapsed = 0.0
+ # Only an absent or nonsensical start time falls back. An elapsed time past the whole budget is
+ # a real answer, and it yields a deadline in the past, so the first step refuses rather than
+ # provisioning a sandbox the activity has no time left to use.
+ return time.monotonic() + budget - max(elapsed, 0.0)
+
+
+def _step_timeout(deadline: float, ceiling_seconds: int) -> int:
+ """Seconds the next sandbox step may take: its own ceiling, or the rest of the budget.
+
+ Every step inside the review activity shares one deadline, so a step that runs long
+ shortens the next one instead of pushing the activity past its start-to-close timeout.
+ Temporal kills the activity at that timeout with no verdict and no notice for the author,
+ so the phases must not be able to over-commit the budget between them.
+ """
+ remaining = int(deadline - time.monotonic())
+ if remaining <= 0:
+ raise RuntimeError("the review budget ran out before the sandbox phase finished")
+ return min(ceiling_seconds, remaining)
+
+
@activity.defn
@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()
run = _load_run(input)
# A newer relevant delivery for the same PR may have superseded this run while it queued — even
@@ -656,10 +699,21 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
run.output = {**latest_output, "sandbox_started_at": timezone.now().isoformat()}
run.save(update_fields=["output", "updated_at"])
+ # 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)
sandbox = sandbox_class.create(config)
try:
- _clone_pr(sandbox, repo, base_sha, run.head_sha, run.pull_request.pr_number, token)
+ _clone_pr(sandbox, repo, base_sha, run.head_sha, run.pull_request.pr_number, token, deadline)
+ _prefetch_review_blobs(sandbox, base_sha, run.head_sha, token, _blame_paths(files), deadline)
+ # The prefetch swallows its own failure, including a timeout that consumed the rest
+ # of the budget. Re-check here, because the three steps below write through the
+ # sandbox filesystem API and cannot take a deadline: passing one would switch them
+ # to an exec-based write, which is a different mechanism, not a bounded one.
+ _step_timeout(deadline, REVIEWER_TIMEOUT_SECONDS)
_inject_policy_files(sandbox, policy_files)
_ship_engine(sandbox)
_write_context(sandbox, invocation)
@@ -667,7 +721,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
command = (
f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && {_harden_reviewer_command(invocation.command)}"
)
- result = sandbox.execute(command, timeout_seconds=25 * 60)
+ result = sandbox.execute(command, timeout_seconds=_step_timeout(deadline, REVIEWER_TIMEOUT_SECONDS))
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.
@@ -1234,14 +1288,52 @@ def _scrub_credentials(text: str, *secrets: str) -> str:
return text
-def _clone_pr(sandbox: SandboxBase, repo: str, base_sha: str, head_sha: str, pr_number: int, token: str) -> None:
+@frozen
+class _GitCredential:
+ """The installation token in the two shapes a sandbox git command needs.
+
+ Both are strings, so they are named rather than returned as a pair — handing the secret to the
+ shell, or the command prefix to the scrubber, would be silent either way.
+ """
+
+ # The ``git`` prefix to run GitHub-facing commands with.
+ command: str
+ # The raw credential, for _scrub_credentials to strip from anything the command echoes back.
+ secret: str = field(repr=False)
+
+
+def _git_credential(token: str) -> _GitCredential:
+ """Build the git invocation that carries the installation token.
+
+ The token rides in a per-invocation ``http.extraheader`` rather than in the remote URL, so git
+ never writes it to ``.git/config`` inside the checkout the reviewer reads. Every command that
+ talks to GitHub from the sandbox builds its git invocation here, so that property holds for all
+ of them rather than for whichever one was written first.
+ """
+ basic = base64.b64encode(f"x-access-token:{token}".encode()).decode()
+ return _GitCredential(
+ command=f"git -c http.extraheader={shlex.quote(f'AUTHORIZATION: basic {basic}')}",
+ secret=basic,
+ )
+
+
+def _clone_pr(
+ sandbox: SandboxBase, repo: str, base_sha: str, head_sha: str, pr_number: int, token: str, deadline: float
+) -> None:
"""Clone the repo with full history, then fetch the PR base and head and check out head.
Full history (no ``--depth``) is required so git-blame familiarity resolves: the
engine blames ``merge-base(base, head)`` for the diff's base-side lines, which needs
- the merge-base commit AND the file history behind it present with real blobs. A
- shallow clone would truncate blame to the graft boundary (undercounting, which only
- ever weakens the signal — a one-way ratchet — but is still avoidable here).
+ the merge-base commit AND the file history behind it present. A shallow clone would
+ truncate blame to the graft boundary (undercounting, which only ever weakens the
+ signal — a one-way ratchet — but is still avoidable here).
+
+ ``--filter=blob:none`` keeps every commit and tree, so history stays complete and blame
+ still walks it; only file contents stay on the remote until something reads them. An
+ unfiltered clone of a monorepo does not finish inside the step timeout, because it carries
+ every blob of every commit. The head checkout batches the blobs it needs into one fetch, and
+ _prefetch_review_blobs batches the old-side ones the review reads, because left to itself blame
+ fetches them one object at a time.
The head is fetched through ``pull/<n>/head`` rather than the bare sha: a fork PR's
head commit only exists in the base repo through that ref, so a bare-sha fetch fails
@@ -1251,12 +1343,10 @@ def _clone_pr(sandbox: SandboxBase, repo: str, base_sha: str, head_sha: str, pr_
checkout of the recorded sha fails and the superseding run takes over — a stale sha
must not be reviewed against a newer pull ref.
- The installation token is passed via a per-invocation ``http.extraheader`` rather than
- embedded in the remote URL, so git never persists it to ``.git/config`` inside the
- checkout that the engine (and LLM reviewer) reads. The remote stays a clean, tokenless URL.
+ The remote stays a clean, tokenless URL — see _git_with_auth for how the token reaches git.
"""
- basic = base64.b64encode(f"x-access-token:{token}".encode()).decode()
- auth = f"git -c http.extraheader={shlex.quote(f'AUTHORIZATION: basic {basic}')}"
+ credential = _git_credential(token)
+ auth = credential.command
repo_url = f"https://github.com/{repo}.git"
def _execute_or_raise(command: str, failure_prefix: str) -> None:
@@ -1265,25 +1355,160 @@ def _clone_pr(sandbox: SandboxBase, repo: str, base_sha: str, head_sha: str, pr_
# Temporal failure details and run.error. Scrub any raised exception (from None so the unscrubbed
# original context isn't chained), and keep scrubbing stderr on a non-zero exit.
try:
- result = sandbox.execute(command, timeout_seconds=10 * 60)
+ result = sandbox.execute(command, timeout_seconds=_step_timeout(deadline, CLONE_STEP_TIMEOUT_SECONDS))
except Exception as exc:
- raise RuntimeError(_scrub_credentials(str(exc), token, basic)) from None
+ raise RuntimeError(_scrub_credentials(str(exc), token, credential.secret)) from None
if result.exit_code != 0:
- raise RuntimeError(f"{failure_prefix}: {_scrub_credentials(result.stderr, token, basic)[:500]}")
+ raise RuntimeError(f"{failure_prefix}: {_scrub_credentials(result.stderr, token, credential.secret)[:500]}")
clone = (
f"rm -rf {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && "
- f"{auth} clone --single-branch {shlex.quote(repo_url)} {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)}"
+ f"{auth} clone --single-branch --filter=blob:none "
+ f"{shlex.quote(repo_url)} {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)}"
)
_execute_or_raise(clone, f"Failed to clone {repo}")
fetch_specs = f"{auth} fetch origin {shlex.quote(f'pull/{pr_number}/head')}"
if base_sha:
fetch_specs = f"{auth} fetch origin {shlex.quote(base_sha)} && {fetch_specs}"
- checkout = f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && {fetch_specs} && git checkout {shlex.quote(head_sha)}"
+ # The checkout carries the credential because it materializes the head tree: on a filtered
+ # clone that reads blobs the fetches above deliberately left on the remote, and git hands the
+ # -c settings to the promisor fetch it spawns. Without it that fetch is anonymous, which a
+ # private repository refuses.
+ checkout = (
+ f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && {fetch_specs} && {auth} checkout {shlex.quote(head_sha)}"
+ )
_execute_or_raise(checkout, f"Failed to check out {head_sha}")
+# Bounds the blame history walk. The engine blames at most 30 files, and this list is ordered the
+# same way, so the bound keeps headroom over that while stopping a pathological file list from
+# making the walk longer than anything will read.
+_MAX_BLAME_PREFETCH_PATHS = 100
+
+# Mirrors _MAX_CHANGED_LINES_PER_FILE in the engine's familiarity.py, which the backend cannot
+# import. Over-naming a path is cheap, but a file this large is one the engine drops before it
+# blames anything, and its history is the most expensive to fetch.
+_MAX_PREFETCH_CHANGED_LINES = 2000
+
+
+def _blame_paths(files: list[dict]) -> list[str]:
+ """Base-side paths of the changed text files, for the blame prefetch.
+
+ The engine blames the OLD path of each changed file, so a rename resolves through
+ ``previous_filename``. A binary is excluded, because its historical blobs are exactly the big
+ ones not worth fetching, and blame skips it anyway. The test is the changed-line count rather
+ than the presence of a patch: GitHub reports a binary as zero added and zero deleted, while it
+ omits the patch of a large text file the engine will still blame.
+
+ Deliberately wider than the engine's own blame selection (largest 30 files): duplicating that
+ heuristic here would let the two drift apart, and naming a path the engine skips costs one more
+ tree walk, because the enumeration reads local trees and the fetch is one request either way.
+ The size bound is the exception, because there the cost is the fetch itself.
+
+ Ordered by changed lines, the way the engine orders its own blame selection. Taking the API's
+ order instead would bound a different set: the engine blames the largest files, so a large one
+ late in the API list would be blamed with nothing prefetched for it.
+ """
+ candidates = [entry for entry in files if 0 < entry.get("changes", 0) <= _MAX_PREFETCH_CHANGED_LINES]
+ candidates.sort(key=lambda entry: entry.get("changes", 0), reverse=True)
+ paths: list[str] = []
+ for entry in candidates:
+ path = entry.get("previous_filename") or entry.get("filename")
+ if path and path not in paths:
+ paths.append(path)
+ return paths[:_MAX_BLAME_PREFETCH_PATHS]
+
+
+def _prefetch_review_blobs(
+ sandbox: SandboxBase,
+ base_sha: str,
+ head_sha: str,
+ token: str,
+ blame_paths: list[str],
+ deadline: float,
+) -> None:
+ """Fetch the old-side blobs the review reads, in one request.
+
+ On a blobless clone blame is the worst case git has: it reads the file's content at each
+ candidate commit, and each miss is its own round trip — for one PR's blame set, ~400 sequential
+ fetches and over three minutes. Enumerating the missing blobs first costs nothing, because the
+ trees are already local, and one batched fetch then serves the whole set, after which blame
+ runs offline in seconds.
+
+ Two sets, one fetch. The blame set needs every historical revision of its paths, which is why it
+ is bounded. The diff set needs the merge-base revision of every changed file, because the engine
+ diffs merge-base against head before it does anything else, and a missing old side there fails
+ the diff outright rather than degrading it.
+
+ ``diff --raw`` names the diff set: with rename detection off it compares tree entries, so it
+ reads no content and needs no blobs, and it reports the old-side object id of every changed
+ file. Asking git rather than the changed-file list from the API keeps this exhaustive — the API
+ pages out on a very large PR, and the diff runs before the size gate that would refuse one.
+ Gitlinks are dropped because a submodule's commit belongs to another repository and origin
+ rejects the whole batch for it; added files are dropped because they have no old side.
+
+ Each of those ids is tested with ``cat-file -e``, whose contract is only its exit status, so the
+ result does not depend on how a given git version reports a missing promisor object — some print
+ it, some fail the command. The blame set uses ``rev-list --missing=print`` instead, which is the
+ documented way to ask that question of a traversal.
+
+ Best effort by design. Everything here is also reachable by a lazy fetch, so a failure costs the
+ review speed rather than its verdict wherever that fetch can authenticate. Anything raised is
+ swallowed; the reviewer's own share of the budget shrinks accordingly and the shared deadline
+ keeps that bounded.
+
+ ``GIT_NO_LAZY_FETCH`` guards each enumeration: without it, the reads would fetch the very
+ objects they are supposed to be reporting as missing. ``fetch.negotiationAlgorithm=noop``
+ skips the have/want negotiation, which walks history to tell the server what the clone already
+ holds — wasted work when the request names the objects it wants outright.
+ """
+ if not base_sha:
+ return
+
+ credential = _git_credential(token)
+ oid_file = "/tmp/stamphog-review-oids"
+ auth = credential.command
+ # rev-list walks history for the blame set; diff --raw names the diff set, and cat-file reports
+ # which of those blobs are absent. The two lists overlap, hence sort -u.
+ history_oids = (
+ (
+ f"GIT_NO_LAZY_FETCH=1 git --literal-pathspecs rev-list --full-history --objects "
+ f'--no-object-names --missing=print "$merge_base" -- '
+ f"{' '.join(shlex.quote(path) for path in blame_paths)} | sed -n 's/^?//p'"
+ )
+ if blame_paths
+ else "true"
+ )
+ diff_oids = (
+ "for oid in $("
+ 'GIT_NO_LAZY_FETCH=1 git diff --raw --no-renames --abbrev=40 "$merge_base" HEAD '
+ "| grep -v '^:160000' | cut -d' ' -f3 | grep -v '^0*$'"
+ '); do GIT_NO_LAZY_FETCH=1 git cat-file -e "$oid" 2>/dev/null || echo "$oid"; done'
+ )
+ command = (
+ f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && "
+ f"merge_base=$(git merge-base {shlex.quote(base_sha)} {shlex.quote(head_sha)}) && "
+ f"{{ {history_oids}; {diff_oids}; }} | sort -u > {shlex.quote(oid_file)} && "
+ f"if [ -s {shlex.quote(oid_file)} ]; then "
+ f"{auth} -c fetch.negotiationAlgorithm=noop fetch origin --no-tags --no-write-fetch-head "
+ f"--filter=blob:none --stdin < {shlex.quote(oid_file)}; fi"
+ )
+ timeout_seconds = _step_timeout(deadline, PREFETCH_BLAME_TIMEOUT_SECONDS)
+ try:
+ result = sandbox.execute(command, timeout_seconds=timeout_seconds)
+ except Exception:
+ activity.logger.warning("stamphog: review blob prefetch failed; git will fetch as it reads")
+ return
+ if result.exit_code != 0:
+ # Scrubbed: the command carries the installation token in an http.extraheader, and a git
+ # failure can echo the argv back.
+ activity.logger.warning(
+ f"stamphog: review blob prefetch exited {result.exit_code}; "
+ f"git will fetch as it reads: {_scrub_credentials(result.stderr, token, credential.secret)[:300]}"
+ )
+
+
def _read_default_policy_file(path: str) -> str:
"""Read a shipped default by the policy path's basename; missing means a server packaging bug."""
default_file = _POLICY_DEFAULTS_DIR / Path(path).name
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index 883362ac9880..5f605f3cac1e 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -68,6 +68,17 @@ STAMPHOG_OPTIONAL_POLICY_PATHS: tuple[str, ...] = (STAMPHOG_STEERING_PATH,)
# Per-activity start-to-close timeouts.
FETCH_CONTEXT_TIMEOUT = timedelta(minutes=5)
RUN_REVIEW_TIMEOUT = timedelta(minutes=30)
+
+# 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
+# independent budget was the bug — the clone alone could hold the activity for twice its ceiling.
+CLONE_STEP_TIMEOUT_SECONDS = 5 * 60
+PREFETCH_BLAME_TIMEOUT_SECONDS = 3 * 60
+REVIEWER_TIMEOUT_SECONDS = 25 * 60
+# Held back from the deadline so a step that runs to its limit still leaves room for the sandbox
+# teardown and the terminal save that follow it.
+SANDBOX_PHASE_RESERVE_SECONDS = 2 * 60
POST_VERDICT_TIMEOUT = timedelta(minutes=5)
MARK_FAILED_TIMEOUT = timedelta(minutes=1)
diff --git a/products/stamphog/backend/tests/test_policy_defaults.py b/products/stamphog/backend/tests/test_policy_defaults.py
index 03b6fb1adf38..71d0f334d8d4 100644
--- a/products/stamphog/backend/tests/test_policy_defaults.py
+++ b/products/stamphog/backend/tests/test_policy_defaults.py
@@ -1,4 +1,5 @@
import sys
+import time
from pathlib import Path
import pytest
@@ -14,12 +15,19 @@ sys.path.insert(0, str(_ENGINE_DIR))
import gates # noqa: E402
import policy # noqa: E402
-from products.stamphog.backend.temporal.activities import _effective_policy_files, _inject_policy_files # noqa: E402
+from products.stamphog.backend.temporal.activities import ( # noqa: E402
+ _blame_paths,
+ _clone_pr,
+ _effective_policy_files,
+ _inject_policy_files,
+ _prefetch_review_blobs,
+)
from products.stamphog.backend.temporal.constants import ( # noqa: E402
STAMPHOG_POLICY_ENTRYPOINT,
STAMPHOG_REVIEW_GUIDANCE_PATH,
STAMPHOG_STEERING_PATH,
)
+from products.stamphog.backend.tests.fakes import FakeExecResult # noqa: E402
_DEFAULT_POLICY = Path(__file__).resolve().parents[1] / "logic" / "policy_defaults" / "policy.yml"
@@ -116,3 +124,63 @@ def test_inject_policy_files_wipes_optional_paths_from_pr_head() -> None:
wipes = [cmd for cmd in executed if cmd.startswith("rm -f")]
assert any(".stamphog/steering.md" in cmd for cmd in wipes)
assert any(".stamphog/policy.yml" in cmd for cmd in wipes)
+
+
+def test_clone_is_blobless_and_blame_blobs_are_prefetched_in_one_fetch() -> None:
+ executed: list[str] = []
+
+ class _RecordingSandbox:
+ def execute(self, command: str, timeout_seconds: int | None = None) -> FakeExecResult:
+ executed.append(command)
+ return FakeExecResult(stdout="", stderr="", exit_code=0)
+
+ deadline = time.monotonic() + 600
+ sandbox = _RecordingSandbox()
+ _clone_pr(sandbox, "acme/widgets", "basesha", "headsha", 7, "tok", deadline) # type: ignore[arg-type]
+ _prefetch_review_blobs(sandbox, "basesha", "headsha", "tok", ["src/old_name.py"], deadline) # type: ignore[arg-type]
+
+ clone = next(cmd for cmd in executed if " clone " in cmd)
+ assert "--filter=blob:none" in clone
+ assert "--depth" not in clone
+
+ # The checkout materializes the head tree, so its promisor fetch needs the credential that
+ # every other GitHub-facing command in the clone carries.
+ checkout = next(cmd for cmd in executed if " checkout " in cmd)
+ assert "http.extraheader" in checkout.split(" checkout ")[0]
+
+ prefetch = next(cmd for cmd in executed if "rev-list" in cmd)
+ assert "--missing=print" in prefetch
+ assert "src/old_name.py" in prefetch
+ # One fetch for the whole set, driven by the enumerated object ids.
+ assert "fetch origin" in prefetch and "--stdin" in prefetch
+ # The enumeration must not fetch the objects it is reporting as missing.
+ assert "GIT_NO_LAZY_FETCH=1" in prefetch
+ # The diff reads the old side of every changed file, so the diff set comes from git rather
+ # than the API file list, which pages out on a large PR.
+ assert "diff --raw --no-renames" in prefetch
+ # A submodule's commit belongs to another repository; batching it makes origin reject the lot.
+ assert "grep -v '^:160000'" in prefetch
+
+
+def test_blame_paths_uses_the_base_side_path_and_skips_binaries() -> None:
+ files = [
+ {"filename": "src/new_name.py", "previous_filename": "src/old_name.py", "patch": "@@", "changes": 4},
+ {"filename": "src/plain.py", "patch": "@@", "changes": 2},
+ # GitHub reports a binary as zero added and zero deleted, and renders no patch for it.
+ {"filename": "static/logo.png", "additions": 0, "deletions": 0, "changes": 0},
+ ]
+ assert _blame_paths(files) == ["src/old_name.py", "src/plain.py"]
+
+ # The engine blames the largest files, so the bounded list has to be ordered the same way: a
+ # large file late in the API order must not be blamed with nothing prefetched for it.
+ ordered = _blame_paths(
+ [
+ {"filename": "src/small.py", "patch": "@@", "changes": 3},
+ {"filename": "src/large.py", "patch": "@@", "changes": 900},
+ ]
+ )
+ assert ordered == ["src/large.py", "src/small.py"]
+
+ # GitHub omits the patch of a large text file too, but reports its real line counts. The engine
+ # parses the local diff and blames it, so it has to be prefetched.
+ assert _blame_paths([{"filename": "src/huge.py", "changes": 1800}]) == ["src/huge.py"]
diff --git a/products/stamphog/packages/pr-approval-agent/familiarity.py b/products/stamphog/packages/pr-approval-agent/familiarity.py
index 75d829395df2..2bf43bfda56b 100644
--- a/products/stamphog/packages/pr-approval-agent/familiarity.py
+++ b/products/stamphog/packages/pr-approval-agent/familiarity.py
@@ -59,6 +59,9 @@ class AuthorFamiliarity:
files_prev_count: int
files_total: int
capped: bool
+ # Files whose blame failed. Their lines count as not owned, so a non-zero value means
+ # blame_overlap_pct is a floor rather than a reading.
+ blame_incomplete_files: int
# Display-only hint: top prior authors of the modified lines, by git author
# name (not login) - used to suggest reviewers when the LLM escalates.
top_prior_authors: tuple[str, ...]
@@ -78,6 +81,7 @@ def familiarity_evidence(fam: AuthorFamiliarity | None) -> dict | None:
"files_prev_count": fam.files_prev_count,
"files_total": fam.files_total,
"capped": fam.capped,
+ "blame_incomplete_files": fam.blame_incomplete_files,
"top_prior_authors": list(fam.top_prior_authors),
}
@@ -288,12 +292,27 @@ def _blame_file(
return _parse_blame_porcelain(result.stdout)
-def _blame_overlap(
- considered: list[_FileDiff], blame_sha: str, author_prs: set[int], repo_root: Path
-) -> tuple[int, int, tuple[str, ...]]:
- """(owned lines, total blamed lines, top prior author names)."""
+@dataclass(frozen=True)
+class _BlameOverlap:
+ """How much of the code a PR changes was written by its author.
+
+ The two line counts share a type, so they are named rather than returned as a pair: swapping
+ them silently inverts the signal the STRONG band reads.
+ """
+
+ owned_lines: int
+ total_lines: int
+ # Files whose blame failed. Their lines count towards total_lines and never towards
+ # owned_lines, so the percentage is a floor whenever this is non-zero.
+ incomplete_files: int
+ # Display-only: top prior authors of the lines the PR author does not own.
+ top_prior_authors: tuple[str, ...]
+
+
+def _blame_overlap(considered: list[_FileDiff], blame_sha: str, author_prs: set[int], repo_root: Path) -> _BlameOverlap:
owned = 0
total = 0
+ incomplete = 0
author_line_counts: Counter[str] = Counter()
for file_diff in considered:
blame_path = file_diff.old_path
@@ -304,6 +323,11 @@ def _blame_overlap(
continue
entries = _blame_file(blame_sha, blame_path, ranges, repo_root)
if entries is None:
+ # A file whose blame fails still owes its lines to the denominator. Dropping it from
+ # both sides would let unread evidence raise the percentage; charging the lines as
+ # unowned can only lower it, which is the direction the signal may safely be wrong in.
+ total += sum(end - start + 1 for start, end in ranges)
+ incomplete += 1
continue
for author_name, summary in entries:
total += 1
@@ -314,8 +338,12 @@ def _blame_overlap(
# Reviewer-suggestion hint: count only lines the PR author does
# NOT own, since suggesting the author to themselves is noise.
author_line_counts[author_name] += 1
- top_authors = tuple(name for name, _ in author_line_counts.most_common(_TOP_PRIOR_AUTHORS))
- return owned, total, top_authors
+ return _BlameOverlap(
+ owned_lines=owned,
+ total_lines=total,
+ incomplete_files=incomplete,
+ top_prior_authors=tuple(name for name, _ in author_line_counts.most_common(_TOP_PRIOR_AUTHORS)),
+ )
# ── prior PRs / last touch / previously-modified files ───────────
@@ -375,13 +403,17 @@ def _files_previously_modified(considered: list[_FileDiff], author_prs: set[int]
of a renamed file, since `git log --name-only -- <new_path>` alone misses
commits recorded under the pre-rename name - the file itself still counts
once towards the total either way.
+
+ ``--no-renames``: rename detection compares blob contents, and on a blobless checkout that is a
+ fetch per commit. The old/new path union above already covers renames, so the detection only
+ buys latency.
"""
if not considered:
return 0, 0
all_paths = sorted({p for f in considered for p in (f.old_path, f.new_path) if p})
if not all_paths:
return 0, len(considered)
- cmd = ["git", "log", f"--since={_LOG_SINCE}", "--format=%x01%s", "--name-only", "--", *all_paths]
+ cmd = ["git", "log", f"--since={_LOG_SINCE}", "--format=%x01%s", "--name-only", "--no-renames", "--", *all_paths]
try:
result = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True, timeout=_GIT_TIMEOUT_SECONDS)
except (OSError, subprocess.SubprocessError):
@@ -462,11 +494,12 @@ def compute_familiarity(
considered_paths = [f.path for f in considered if f.path]
blame_sha = _merge_base(base_sha, head_sha, repo_root)
- if blame_sha is not None:
- owned, total, top_authors = _blame_overlap(considered, blame_sha, author_prs, repo_root)
- else:
- owned, total, top_authors = 0, 0, ()
- blame_overlap_pct = (100.0 * owned / total) if total else 0.0
+ overlap = (
+ _blame_overlap(considered, blame_sha, author_prs, repo_root)
+ if blame_sha is not None
+ else _BlameOverlap(owned_lines=0, total_lines=0, incomplete_files=0, top_prior_authors=())
+ )
+ blame_overlap_pct = (100.0 * overlap.owned_lines / overlap.total_lines) if overlap.total_lines else 0.0
prior_prs, days_since = _prior_prs_in_paths(considered_paths, author_prs, repo_root, now)
files_prev_count, files_total = _files_previously_modified(considered, author_prs, repo_root)
@@ -476,12 +509,13 @@ def compute_familiarity(
return AuthorFamiliarity(
band=band,
blame_overlap_pct=blame_overlap_pct,
- modified_lines_owned=owned,
- modified_lines_total=total,
+ modified_lines_owned=overlap.owned_lines,
+ modified_lines_total=overlap.total_lines,
prior_prs_in_paths=prior_prs,
days_since_last_touch=days_since,
files_prev_count=files_prev_count,
files_total=files_total,
capped=capped,
- top_prior_authors=top_authors,
+ blame_incomplete_files=overlap.incomplete_files,
+ top_prior_authors=overlap.top_prior_authors,
)
diff --git a/products/stamphog/packages/pr-approval-agent/review_local.py b/products/stamphog/packages/pr-approval-agent/review_local.py
index efc8f1dfd971..1c28e04dbb46 100644
--- a/products/stamphog/packages/pr-approval-agent/review_local.py
+++ b/products/stamphog/packages/pr-approval-agent/review_local.py
@@ -47,6 +47,7 @@ from familiarity import (
AuthorFamiliarity,
_band,
_blame_overlap,
+ _BlameOverlap,
_files_previously_modified,
_merge_base,
_parse_diff,
@@ -309,11 +310,12 @@ def _familiarity_offline(
considered_paths = [f.path for f in considered if f.path]
blame_sha = _merge_base(base_sha, head_sha, REPO_ROOT)
- if blame_sha is not None:
- owned, total, top_authors = _blame_overlap(considered, blame_sha, author_prs, REPO_ROOT)
- else:
- owned, total, top_authors = 0, 0, ()
- blame_overlap_pct = (100.0 * owned / total) if total else 0.0
+ overlap = (
+ _blame_overlap(considered, blame_sha, author_prs, REPO_ROOT)
+ if blame_sha is not None
+ else _BlameOverlap(owned_lines=0, total_lines=0, incomplete_files=0, top_prior_authors=())
+ )
+ blame_overlap_pct = (100.0 * overlap.owned_lines / overlap.total_lines) if overlap.total_lines else 0.0
prior_prs, days_since = _prior_prs_in_paths(considered_paths, author_prs, REPO_ROOT, now)
files_prev_count, files_total = _files_previously_modified(considered, author_prs, REPO_ROOT)
@@ -322,14 +324,15 @@ def _familiarity_offline(
return AuthorFamiliarity(
band=band,
blame_overlap_pct=blame_overlap_pct,
- modified_lines_owned=owned,
- modified_lines_total=total,
+ modified_lines_owned=overlap.owned_lines,
+ modified_lines_total=overlap.total_lines,
prior_prs_in_paths=prior_prs,
days_since_last_touch=days_since,
files_prev_count=files_prev_count,
files_total=files_total,
capped=capped,
- top_prior_authors=top_authors,
+ blame_incomplete_files=overlap.incomplete_files,
+ top_prior_authors=overlap.top_prior_authors,
)
diff --git a/products/stamphog/packages/pr-approval-agent/test_familiarity.py b/products/stamphog/packages/pr-approval-agent/test_familiarity.py
index a90518f9451c..68eba7385d01 100644
--- a/products/stamphog/packages/pr-approval-agent/test_familiarity.py
+++ b/products/stamphog/packages/pr-approval-agent/test_familiarity.py
@@ -200,6 +200,44 @@ def test_capped_flag_set_when_file_exceeds_line_bound(tmp_path: Path, monkeypatc
assert fam.modified_lines_total == 0
+def test_failed_blame_counts_its_lines_as_not_owned(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ repo = tmp_path / "repo"
+ _init_repo(repo)
+ _commit(repo, "src/mine.py", _numbered_lines("mine", 4), "feat: mine (#1)", "authora")
+ _commit(repo, "src/theirs.py", _numbered_lines("theirs", 4), "feat: theirs (#2)", "authorb")
+ base_sha = _head(repo)
+ (repo / "src/mine.py").write_text(_numbered_lines("mine", 4).replace("mine 2\n", "mine 2 changed\n"))
+ (repo / "src/theirs.py").write_text(_numbered_lines("theirs", 4).replace("theirs 2\n", "theirs 2 changed\n"))
+ diff_path = tmp_path / "pr.diff"
+ diff_path.write_text(_git(repo, "diff", base_sha).stdout)
+
+ real_run = familiarity.subprocess.run
+
+ def fail_blame_of_theirs(cmd, *args, **kwargs):
+ if cmd[:2] == ["git", "blame"] and "src/theirs.py" in cmd:
+ raise OSError("blame could not read a missing object")
+ return real_run(cmd, *args, **kwargs)
+
+ monkeypatch.setattr(familiarity.subprocess, "run", fail_blame_of_theirs)
+ _patch_gh(monkeypatch, pr_numbers={1})
+ fam = compute_familiarity(
+ author_login="authora",
+ diff_path=diff_path,
+ base_sha=base_sha,
+ head_sha="HEAD",
+ repo="PostHog/posthog",
+ repo_root=repo,
+ thresholds=_THRESHOLDS,
+ )
+
+ assert fam is not None
+ assert fam.blame_incomplete_files == 1
+ # One line owned out of two changed lines, not one out of one.
+ assert fam.modified_lines_owned == 1
+ assert fam.modified_lines_total == 2
+ assert fam.blame_overlap_pct == 50.0
+
+
def test_files_previously_modified_counts_renamed_file_by_old_path(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -361,6 +399,7 @@ def _fam(band: str, top_authors: tuple[str, ...]) -> AuthorFamiliarity:
files_prev_count=0,
files_total=3,
capped=False,
+ blame_incomplete_files=0,
top_prior_authors=top_authors,
)
diff --git a/products/stamphog/packages/pr-approval-agent/test_policy.py b/products/stamphog/packages/pr-approval-agent/test_policy.py
index 5b6fb7b39e56..adde7ed3a8b0 100644
--- a/products/stamphog/packages/pr-approval-agent/test_policy.py
+++ b/products/stamphog/packages/pr-approval-agent/test_policy.py
@@ -715,6 +715,7 @@ def test_review_body_leads_with_reasoning_and_folds_mechanics() -> None:
files_prev_count=1,
files_total=1,
capped=False,
+ blame_incomplete_files=0,
top_prior_authors=(),
)
body = _body_pipeline(fam)._render_review_body()
diff --git a/products/stamphog/packages/pr-approval-agent/test_review_pr.py b/products/stamphog/packages/pr-approval-agent/test_review_pr.py
index 4b3b2df1841c..a449e882ca13 100644
--- a/products/stamphog/packages/pr-approval-agent/test_review_pr.py
+++ b/products/stamphog/packages/pr-approval-agent/test_review_pr.py
@@ -634,6 +634,7 @@ def test_familiarity_computed_on_every_tier_but_prompted_only_on_t1(
files_prev_count=2,
files_total=3,
capped=False,
+ blame_incomplete_files=0,
top_prior_authors=(),
)
pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
@@ -681,6 +682,7 @@ def test_capture_review_completed_includes_familiarity_and_provenance(
files_prev_count=1,
files_total=3,
capped=False,
+ blame_incomplete_files=0,
top_prior_authors=("Alice",),
)
pipeline.provenance = CommitProvenance(