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.

feat(review_hog): stamp the PR on review tasks for per-PR cost (#117301)

Georges-Antoine Assid037e88360c1
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 1ab411a0adf3..98f22813c5a3 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -594,6 +594,9 @@ The agent returns JSON at the end of each turn; the caller validates it and ends
failure `start` ends its own session and raises, so the helper logs and returns **`None`**. There is no
`output_path` / `_error.txt` and no manual JSON extraction — persistence is the caller's job. The runner
persists the full agent log at `task_run.log_url` (S3 / Tasks UI), so the executor never copies it locally.
+ Each task also gets an `origin_key` of `{random}:{workflow_id_prefix}` (the prefix holds `owner/repo:pr_number`),
+ which lands on `$ai_generation` as `task_origin_key` so review cost can be summed per PR.
+ The key caps at 128 characters: only the step text is cut, and an owner/repo too long to fit becomes a stable digest, so the PR number always survives.
The perspective review (the blind-spot sweep rides the same activity) runs on a different model family than the
rest — **OpenAI Codex `gpt-6.1-sol`**, with `initial_permission_mode="full-access"`, at an effort set by the
diff --git a/products/review_hog/backend/reviewer/sandbox/executor.py b/products/review_hog/backend/reviewer/sandbox/executor.py
index 0fa23dcb05a9..1ef59cd40ec1 100644
--- a/products/review_hog/backend/reviewer/sandbox/executor.py
+++ b/products/review_hog/backend/reviewer/sandbox/executor.py
@@ -1,3 +1,6 @@
+import re
+import uuid
+import hashlib
import logging
from collections.abc import Sequence
from typing import TypeVar
@@ -13,6 +16,30 @@ _ModelT = TypeVar("_ModelT", bound=BaseModel)
logger = logging.getLogger(__name__)
+TASK_ORIGIN_KEY_MAX_LENGTH = 128
+
+_REVIEW_PR_WORKFLOW_ID = re.compile(r"^(?P<kind>review-pr:\d+:)(?P<repository>[^:]+)(?P<pr>:\d+)(?P<step>.*)$")
+
+
+def _origin_key(workflow_id_prefix: str | None) -> str | None:
+ # Task.origin_key reaches $ai_generation as task_origin_key, and the workflow id holds the PR.
+ # Task allows one origin_key per team, so the unique part leads and survives truncation.
+ if not workflow_id_prefix:
+ return None
+ unique = uuid.uuid4().hex[:12]
+ key = f"{unique}:{workflow_id_prefix}"
+ match = _REVIEW_PR_WORKFLOW_ID.match(workflow_id_prefix)
+ if len(key) <= TASK_ORIGIN_KEY_MAX_LENGTH or match is None:
+ return key[:TASK_ORIGIN_KEY_MAX_LENGTH]
+ # Only the step may be cut, so a long owner/repo becomes a stable digest that keeps PRs apart.
+ repository = match["repository"]
+ pr_identity = f"{unique}:{match['kind']}{repository}{match['pr']}"
+ if len(pr_identity) > TASK_ORIGIN_KEY_MAX_LENGTH:
+ digest = hashlib.sha256(repository.encode()).hexdigest()[:16]
+ pr_identity = f"{unique}:{match['kind']}{digest}{match['pr']}"
+ return f"{pr_identity}{match['step']}"[:TASK_ORIGIN_KEY_MAX_LENGTH]
+
+
# Sent once when the agent ends its first turn with prose instead of the JSON the step needs.
JSON_RETRY_PROMPT = (
"Your last reply did not contain the JSON object the task asks for. "
@@ -49,6 +76,7 @@ async def _run_prompt(
branch=branch or None,
step_name=step_name,
workflow_id_prefix=workflow_id_prefix,
+ origin_key=_origin_key(workflow_id_prefix),
# ReviewHog-attributed and internal (pipeline plumbing, not a user-facing task); the step
# lands on $ai_generation as ai_stage for per-stage cost attribution.
origin_product=TaskOriginProduct.REVIEW_HOG,
@@ -176,6 +204,7 @@ async def start_sandbox_session(
branch=branch or None,
step_name=step_name,
workflow_id_prefix=workflow_id_prefix,
+ origin_key=_origin_key(workflow_id_prefix),
# Same attribution trio as _run_prompt: ReviewHog-origin, internal, step as ai_stage.
origin_product=TaskOriginProduct.REVIEW_HOG,
internal=True,
diff --git a/products/review_hog/backend/reviewer/tests/test_executor.py b/products/review_hog/backend/reviewer/tests/test_executor.py
index 72f47f3d1cfa..2454beed4bbc 100644
--- a/products/review_hog/backend/reviewer/tests/test_executor.py
+++ b/products/review_hog/backend/reviewer/tests/test_executor.py
@@ -149,6 +149,75 @@ class TestRunSandboxReview:
# The session path builds its own context, so the least-privilege pin must hold here too.
assert call_kwargs["context"].posthog_mcp_scopes == ["llm_skill:read", "user:read"]
+ @parameterized.expand(
+ [
+ ("single_turn_with_prefix", run_sandbox_review, "review-pr:1:o/r:7:chunking", True),
+ ("warm_session_with_prefix", start_sandbox_session, "review-pr:1:o/r:7:validation-c1", True),
+ ("single_turn_without_prefix", run_sandbox_review, None, False),
+ ("warm_session_without_prefix", start_sandbox_session, None, False),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_origin_key_carries_the_review_workflow_id(self, _name, entrypoint, prefix, expect_key) -> None:
+ # The workflow id holds the PR (`review-pr:{team}:{owner}/{repo}:{pr}`). Task.origin_key reaches
+ # $ai_generation as task_origin_key, so this is the only way to sum review cost per PR.
+ mock_start = AsyncMock(return_value=(AsyncMock(), DummyModel(result="ok")))
+
+ with patch(f"{_EXECUTOR_PREFIX}.MultiTurnSession.start", mock_start):
+ await entrypoint(
+ team_id=1,
+ user_id=2,
+ repository="o/r",
+ branch="b",
+ prompt="p",
+ system_prompt="s",
+ model_to_validate=DummyModel,
+ workflow_id_prefix=prefix,
+ )
+
+ origin_key = mock_start.call_args.kwargs["origin_key"]
+ if expect_key:
+ assert origin_key.endswith(f":{prefix}")
+ else:
+ assert origin_key is None
+
+ @parameterized.expand(
+ [
+ ("short_prefix", "review-pr:1:o/r:7:chunking", "7"),
+ ("prefix_longer_than_the_column", "review-pr:1:" + "o" * 200 + "/r:7:chunking", "7"),
+ ("max_length_owner_and_repo", "review-pr:1:" + "o" * 39 + "/" + "r" * 100 + ":117301:chunking", "117301"),
+ (
+ "long_owner_and_repo_child_workflow",
+ "review-pr:1:" + "o" * 20 + "/" + "r" * 80 + ":117301/validate:x",
+ "117301/validate",
+ ),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_origin_key_is_unique_per_task_and_fits_the_column(self, _name, prefix, pr_segment) -> None:
+ # Task enforces one origin_key per team (max 128 chars), and one review starts many tasks with
+ # the same prefix, so the unique part must lead and survive truncation.
+ mock_start = AsyncMock(return_value=(AsyncMock(), DummyModel(result="ok")))
+
+ with patch(f"{_EXECUTOR_PREFIX}.MultiTurnSession.start", mock_start):
+ for _ in range(2):
+ await run_sandbox_review(
+ team_id=1,
+ user_id=2,
+ repository="o/r",
+ branch="b",
+ prompt="p",
+ system_prompt="s",
+ model_to_validate=DummyModel,
+ workflow_id_prefix=prefix,
+ )
+
+ first, second = (call.kwargs["origin_key"] for call in mock_start.call_args_list)
+ assert first != second
+ assert len(first) <= 128 and len(second) <= 128
+ assert first.split(":")[1:5] == second.split(":")[1:5]
+ assert first.split(":")[4] == pr_segment
+
@parameterized.expand(
[
("clean_teardown", {}, "completed", None),