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): run standard sessions as sub-agents of one coordinator (#115213)

Julian Bez295e0f5e0437
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.py
index e7d5a5fd8e59..d22c62ab94f1 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -210,6 +210,10 @@ FLASH_LENSES: dict[str, FlashLens] = {
),
}
+# One sub-agent per review unit: the main review and every lens part. Codex runs only 3 sub-agents
+# at once by default, so a larger PR would lose the lenses past that.
+COORDINATOR_MAX_SUBAGENTS = 1 + len(FLASH_LENSES) * FLASH_LENS_MAX_CHUNKS
+
def is_single_agent_pass(pass_number: int) -> bool:
"""Whether a persisted review result came from a single-agent session, the main one or a lens.
diff --git a/products/review_hog/backend/reviewer/feature_flags.py b/products/review_hog/backend/reviewer/feature_flags.py
index 96eb86ed7542..27d349deba8e 100644
--- a/products/review_hog/backend/reviewer/feature_flags.py
+++ b/products/review_hog/backend/reviewer/feature_flags.py
@@ -33,3 +33,24 @@ def flash_pipeline_kill_switch_on(team_id: int) -> bool:
)
return False
return enabled is True
+
+
+STANDARD_COORDINATOR_FLAG = "reviewhog-standard-coordinator"
+
+
+def standard_coordinator_on(repository: str, pr_number: int) -> bool:
+ """Whether this PR's Standard turns run their sessions as sub-agents of one coordinator session.
+
+ Keyed by the PR, not the organization, so a percentage rollout splits the reviews of one organization
+ and every turn of a PR runs on the same design. Any evaluation failure reads as off.
+ """
+ try:
+ enabled = posthoganalytics.feature_enabled(
+ STANDARD_COORDINATOR_FLAG,
+ f"{repository}#{pr_number}",
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ logger.exception("Could not evaluate %s for %s#%s", STANDARD_COORDINATOR_FLAG, repository, pr_number)
+ return False
+ return enabled is True
diff --git a/products/review_hog/backend/reviewer/fingerprint.py b/products/review_hog/backend/reviewer/fingerprint.py
index fa8fe4cd62ad..bca21c04dcf0 100644
--- a/products/review_hog/backend/reviewer/fingerprint.py
+++ b/products/review_hog/backend/reviewer/fingerprint.py
@@ -55,6 +55,7 @@ from products.review_hog.backend.reviewer.skill_loader import (
load_perspectives_for_run,
load_validation_skill_for_run,
)
+from products.review_hog.backend.reviewer.tools.coordinator_review import COORDINATOR_PROMPT_FILE
from products.review_hog.backend.reviewer.tools.issue_deduplicator import DEDUP_SYSTEM_PROMPT
from products.review_hog.backend.reviewer.tools.issue_validation import (
VALIDATION_FOLLOWUP_TEMPLATE,
@@ -230,6 +231,7 @@ class TurnFingerprint:
review_mode: str,
flash_reasoning_effort: str,
review_design: str = REVIEW_DESIGN_PIPELINE,
+ coordinator: bool = False,
) -> TurnFingerprint:
stored_arm = resolve_review_arm(
report.review_runtime_adapter,
@@ -241,8 +243,14 @@ class TurnFingerprint:
review_mode, stored_arm, flash_reasoning_effort=flash_reasoning_effort, review_design=review_design
)
if review_design == REVIEW_DESIGN_SINGLE_AGENT:
+ coordinator_inputs: dict[str, Any] = {}
+ if coordinator:
+ # Only coordinated turns carry it, so turns on separate sessions keep their cohort.
+ prompt = (SINGLE_AGENT_PROMPT_PATH / COORDINATOR_PROMPT_FILE.name).read_text()
+ coordinator_inputs["coordinator"] = {"prompt": _text_hash(prompt)}
return cls(
{
+ **coordinator_inputs,
"review_mode": review_mode,
"review_design": review_design,
"review_arm": _arm_payload(review_arm),
@@ -290,6 +298,7 @@ def record_turn_marker(
review_mode: str,
flash_reasoning_effort: str,
review_design: str = REVIEW_DESIGN_PIPELINE,
+ coordinator: bool = False,
) -> ReviewHogMarker:
"""Compute the turn's marker and persist it as the turn's `turn_marker` artefact."""
report = ReviewReport.objects.for_team(team_id).get(id=report_id)
@@ -300,6 +309,7 @@ def record_turn_marker(
review_mode=review_mode,
flash_reasoning_effort=flash_reasoning_effort,
review_design=review_design,
+ coordinator=coordinator,
)
marker = ReviewHogMarker(
version=reviewhog_version_for_mode(review_mode, review_design), fingerprint=fingerprint.digest()
diff --git a/products/review_hog/backend/reviewer/prompts/single_agent_review/coordinator.md b/products/review_hog/backend/reviewer/prompts/single_agent_review/coordinator.md
new file mode 100644
index 000000000000..47f149f4c35a
--- /dev/null
+++ b/products/review_hog/backend/reviewer/prompts/single_agent_review/coordinator.md
@@ -0,0 +1,26 @@
+<!--
+DevEx-owned prompt of the coordinator session of a Standard review. The builder strips this comment
+and fills in the task lines, the model and the reasoning effort.
+-->
+
+You coordinate the review of one pull request. Sub-agents do the whole review. You do not review the pull request yourself: do not read the code, the diff or the prompt files.
+
+The task of each sub-agent is in one attached file. The attached files are listed at the end of this message, each with its full path.
+
+1. Start these sub-agents now. Call `spawn_agent` once per line below, all of them right away, so that they run in parallel. In each call set `task_name` to the name given, `model` to "<<MODEL>>" and `reasoning_effort` to "<<EFFORT>>", do not fork your conversation into them, and send exactly the message given, with `<path of NAME>` replaced by the full path of the attached file NAME. Send nothing else.
+ <<TASKS>>
+2. Wait for every sub-agent to finish (`wait_agent`). Do not do their work and do not change their findings.
+3. A sub-agent fails when it stops with an error, when its reply has no JSON object with a "findings" list, or when a finding in that list lacks a `title`, `priority`, `file` or `body`, or an integer `line_start`. Start a failed sub-agent once more, with `_retry` added to its task name and the same model, reasoning effort and message. Report its result under the original task name. If it fails again, report it as failed. A sub-agent other than `main_1` that is still running 10 minutes after you started it also counts as failed. Stop it with `interrupt_agent` and do not start it again. Wait for `main_1` until it finishes.
+4. Reply with only this JSON object:
+
+{
+"results": [
+{"task": "<the task name>", "status": "ok", "findings": <the "findings" list of that sub-agent's reply, copied verbatim>},
+{"task": "<the task name>", "status": "failed", "findings": []}
+]
+}
+
+- Put exactly one entry in "results" for each task name above.
+- Copy every finding unchanged, with all its fields. Do not add, drop, merge or reorder findings.
+- Use status "ok" and an empty list for a sub-agent that returned no findings.
+- Do not wrap the JSON in markdown fences or add prose.
diff --git a/products/review_hog/backend/reviewer/sandbox/executor.py b/products/review_hog/backend/reviewer/sandbox/executor.py
index 9b03d18ba117..d337b631ab18 100644
--- a/products/review_hog/backend/reviewer/sandbox/executor.py
+++ b/products/review_hog/backend/reviewer/sandbox/executor.py
@@ -1,4 +1,5 @@
import logging
+from collections.abc import Sequence
from typing import TypeVar
from pydantic import BaseModel
@@ -6,6 +7,7 @@ from pydantic import BaseModel
from products.review_hog.backend.reviewer.constants import REVIEW_MCP_SCOPES
from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession
from products.tasks.backend.facade.api import TaskOriginProduct
+from products.tasks.backend.facade.contracts import SessionFile
_ModelT = TypeVar("_ModelT", bound=BaseModel)
@@ -26,6 +28,7 @@ async def _run_prompt(
branch: str | None = None,
step_name: str = "",
workflow_id_prefix: str | None = None,
+ files: Sequence[SessionFile] = (),
) -> _ModelT:
"""Spawn a single-turn sandbox agent and return its validated end-of-turn.
@@ -52,6 +55,7 @@ async def _run_prompt(
internal=True,
ai_stage=step_name or None,
json_retry_prompt=JSON_RETRY_PROMPT,
+ files=files,
)
except Exception:
logger.exception("Sandbox execution failed")
@@ -77,6 +81,8 @@ async def run_sandbox_review(
model: str | None = None,
reasoning_effort: str | None = None,
initial_permission_mode: str | None = None,
+ files: Sequence[SessionFile] = (),
+ codex_max_subagents: int | None = None,
) -> _ModelT:
"""Run one review step in a sandbox and return its validated output.
@@ -94,7 +100,8 @@ async def run_sandbox_review(
default (Claude). ``model_to_validate`` is the output *schema*, unrelated to ``model``.
``initial_permission_mode`` sets the agent's approval mode — a headless step that calls MCP tools
under Codex must pass ``"full-access"`` or it stalls on an approval prompt (Codex ``"auto"`` does
- not auto-approve MCP tool calls).
+ not auto-approve MCP tool calls). ``files`` go into the sandbox before the first turn, and
+ ``codex_max_subagents`` lets a step that starts Codex sub-agents run more of them at once.
"""
full_prompt = "\n\n".join(part for part in (system_prompt, prompt) if part)
context = CustomPromptSandboxContext(
@@ -104,6 +111,7 @@ async def run_sandbox_review(
model=model,
runtime_adapter=runtime_adapter,
reasoning_effort=reasoning_effort,
+ codex_max_subagents=codex_max_subagents,
initial_permission_mode=initial_permission_mode,
# Unset means "full" — never hand that to a session fed untrusted PR-comment text.
posthog_mcp_scopes=REVIEW_MCP_SCOPES,
@@ -115,6 +123,7 @@ async def run_sandbox_review(
branch=branch,
step_name=step_name,
workflow_id_prefix=workflow_id_prefix,
+ files=files,
)
diff --git a/products/review_hog/backend/reviewer/tools/coordinator_review.py b/products/review_hog/backend/reviewer/tools/coordinator_review.py
new file mode 100644
index 000000000000..980bd4b0078e
--- /dev/null
+++ b/products/review_hog/backend/reviewer/tools/coordinator_review.py
@@ -0,0 +1,88 @@
+"""The coordinator variant of a Standard turn: one sandbox session runs every review unit as a sub-agent.
+
+Each unit is the main review or one lens part, with the prompt its own session would get. The prompts
+reach the sandbox as session files, because the coordinator cannot copy that much text into its
+sub-agent messages in reasonable time.
+"""
+
+import logging
+from collections import Counter
+from typing import Literal
+
+from pydantic import BaseModel, JsonValue, ValidationError
+
+from posthog.dataclasses import frozen
+
+from products.review_hog.backend.reviewer.models.single_agent_review import SingleAgentReview
+from products.review_hog.backend.reviewer.tools.single_agent_review import SINGLE_AGENT_PROMPT_PATH, load_prompt_file
+
+logger = logging.getLogger(__name__)
+
+COORDINATOR_PROMPT_FILE = SINGLE_AGENT_PROMPT_PATH / "coordinator.md"
+TASK_MESSAGE = (
+ "Read the file `<path of {file_name}>` in full ({lines} lines, {chars} characters; read it in parts when one"
+ " read cannot hold all of it). It is your complete task. Follow it exactly and reply with only the JSON object"
+ " it asks for."
+)
+
+
+@frozen
+class CoordinatorUnit:
+ """One sub-agent, keyed like the separate session that would run the same review unit."""
+
+ task_name: str
+ pass_number: int
+ chunk_id: int
+ source: str
+ prompt: str
+
+ @property
+ def file_name(self) -> str:
+ return f"{self.task_name}.prompt.md"
+
+ def task_line(self) -> str:
+ message = TASK_MESSAGE.format(
+ file_name=self.file_name, lines=self.prompt.count("\n") + 1, chars=len(self.prompt)
+ )
+ return f' - task name `{self.task_name}`, message: "{message}"'
+
+
+class CoordinatorResult(BaseModel):
+ task: str
+ status: Literal["ok", "failed"]
+ # Required, so a result without the list fails validation instead of reading as a clean review. Raw, so
+ # one sub-agent's malformed finding fails only that sub-agent.
+ findings: list[JsonValue]
+
+
+class CoordinatorReview(BaseModel):
+ """The coordinator's answer: one result per sub-agent, with its findings copied unchanged."""
+
+ results: list[CoordinatorResult]
+
+ def reviews_by_task(self) -> dict[str, SingleAgentReview]:
+ """The review of every sub-agent that finished with valid findings, by task name."""
+ reviews: dict[str, SingleAgentReview] = {}
+ counts = Counter(result.task for result in self.results)
+ for result in self.results:
+ if result.status != "ok":
+ continue
+ if counts[result.task] > 1:
+ logger.warning(
+ "The coordinator reported sub-agent %s more than once; counting it as failed", result.task
+ )
+ continue
+ try:
+ reviews[result.task] = SingleAgentReview.model_validate({"findings": result.findings})
+ except ValidationError:
+ logger.warning("Sub-agent %s returned malformed findings; counting it as failed", result.task)
+ return reviews
+
+
+def coordinator_prompt(units: list[CoordinatorUnit], *, model: str, reasoning_effort: str) -> str:
+ return (
+ load_prompt_file(COORDINATOR_PROMPT_FILE)
+ .replace("<<MODEL>>", model)
+ .replace("<<EFFORT>>", reasoning_effort)
+ .replace("<<TASKS>>", "\n".join(unit.task_line() for unit in units))
+ )
diff --git a/products/review_hog/backend/temporal/__init__.py b/products/review_hog/backend/temporal/__init__.py
index e11717e4fcc2..c3ebe5faf7a0 100644
--- a/products/review_hog/backend/temporal/__init__.py
+++ b/products/review_hog/backend/temporal/__init__.py
@@ -1,6 +1,7 @@
from products.review_hog.backend.temporal.activities import (
append_code_review_artefact_activity,
build_body_activity,
+ coordinator_review_activity,
dedup_activity,
fail_status_comment_activity,
fetch_pr_data_activity,
@@ -68,6 +69,7 @@ ACTIVITIES = [
review_chunk_activity,
single_agent_review_activity,
lens_review_activity,
+ coordinator_review_activity,
dedup_activity,
load_validation_skill_activity,
validate_chunk_activity,
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 70600dd6ed6a..e0b3c1c64c1f 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -47,6 +47,7 @@ from products.review_hog.backend.reviewer.constants import (
CHUNKING_ONESHOT_MAX_ADDITIONS,
CHUNKING_REASONING_EFFORT,
CHUNKING_RUNTIME_ADAPTER,
+ COORDINATOR_MAX_SUBAGENTS,
FLASH_LENSES,
NON_RETRYABLE_UNIT_FAILURE_CATEGORIES,
REVIEW_MODE_FLASH,
@@ -63,7 +64,7 @@ from products.review_hog.backend.reviewer.constants import (
select_review_design,
validation_arm_for_mode,
)
-from products.review_hog.backend.reviewer.feature_flags import flash_pipeline_kill_switch_on
+from products.review_hog.backend.reviewer.feature_flags import flash_pipeline_kill_switch_on, standard_coordinator_on
from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker, record_turn_marker
from products.review_hog.backend.reviewer.lazy_seed import (
sync_canonical_authoring,
@@ -135,6 +136,11 @@ from products.review_hog.backend.reviewer.status_comment import (
maybe_refresh_status_comment,
)
from products.review_hog.backend.reviewer.telemetry import review_event_uuid, review_routing_properties
+from products.review_hog.backend.reviewer.tools.coordinator_review import (
+ CoordinatorReview,
+ CoordinatorUnit,
+ coordinator_prompt,
+)
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
from products.review_hog.backend.reviewer.tools.github_meta import (
PRFetcher,
@@ -192,6 +198,7 @@ from products.signals.backend.enums import ReportPriority
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
from products.tasks.backend.facade.agents import AgentTurnFailed
+from products.tasks.backend.facade.contracts import SessionFile
from products.tasks.backend.facade.run_config import ReasoningEffort
if TYPE_CHECKING:
@@ -267,6 +274,9 @@ class ReviewMeta:
lens_chunk_count: int = 0
# True when the PR passed the lens part cap, so the status comment says it ran in larger parts.
lens_chunks_capped: bool = False
+ # A single-agent turn that runs its sessions as sub-agents of one coordinator session. Recorded here
+ # so a replay takes the same branch. Older histories decode as separate sessions.
+ coordinator: bool = False
# None means no automatic review has run on the PR, so the push gate stays off for this turn.
automatic_reviewed_head_sha: str | None = None
# An automatic turn on a PR with the skip-agent-review label. Older histories decode as no skip.
@@ -412,6 +422,17 @@ class LensReviewInput(SandboxStageInput):
chunk_id: int
+@dataclass(frozen=False)
+class CoordinatorReviewInput(SandboxStageInput):
+ lens_chunk_count: int
+
+
+@frozen
+class CoordinatorReviewResult:
+ # Lens sub-agents that failed twice or ran out of time. Their findings are missing.
+ lens_failures: int
+
+
@dataclass
class ValidateChunkInput(SandboxStageInput):
chunk_id: int
@@ -524,6 +545,8 @@ class FlashSessionStats:
lens_timeouts: int
# The longest session, main or lens, from its start to its result or failure.
slowest_session_seconds: float
+ # The sessions ran as sub-agents of one coordinator session, and the slowest session is that one.
+ coordinator: bool = False
@frozen
@@ -564,6 +587,7 @@ class RecordTurnMarkerInput:
review_mode: str
flash_reasoning_effort: str
review_design: str = REVIEW_DESIGN_PIPELINE
+ coordinator: bool = False
@frozen
@@ -579,6 +603,7 @@ class TrackReviewStartedInput:
flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
review_design: str = REVIEW_DESIGN_PIPELINE
review_design_reason: str = ""
+ coordinator: bool = False
@frozen
@@ -837,6 +862,7 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:
review_design_reason=design_choice.reason,
lens_chunk_count=len(lens_plan.chunks) if lens_plan is not None else 0,
lens_chunks_capped=lens_plan is not None and lens_plan.capped,
+ coordinator=single_agent and pr_number is not None and standard_coordinator_on(input.repository, pr_number),
automatic_reviewed_head_sha=report.automatic_reviewed_head_sha,
skip_agent_review=skip_agent_review,
)
@@ -1036,6 +1062,7 @@ def _record_turn_marker_safe(input: RecordTurnMarkerInput) -> ReviewHogMarker |
review_mode=input.review_mode,
flash_reasoning_effort=input.flash_reasoning_effort,
review_design=input.review_design,
+ coordinator=input.coordinator,
)
except Exception:
logger.exception("Failed to record the turn marker for report %s; continuing", input.report_id)
@@ -1470,6 +1497,110 @@ async def lens_review_activity(input: LensReviewInput) -> None:
)
+def _coordinator_units(input: CoordinatorReviewInput, done: set[tuple[int, int]]) -> list[CoordinatorUnit]:
+ """The review units of this turn that have no persisted result yet, each with its full session prompt."""
+ units: list[CoordinatorUnit] = []
+ if (SINGLE_AGENT_PASS_NUMBER, SINGLE_AGENT_CHUNK_ID) not in done:
+ units.append(
+ CoordinatorUnit(
+ task_name=f"main_{SINGLE_AGENT_CHUNK_ID}",
+ pass_number=SINGLE_AGENT_PASS_NUMBER,
+ chunk_id=SINGLE_AGENT_CHUNK_ID,
+ source=SINGLE_AGENT_SOURCE,
+ prompt=_prepare_single_agent_prompt(input, SINGLE_AGENT_CHUNK_ID, False, load_core_prompt()),
+ )
+ )
+ for name, lens in FLASH_LENSES.items():
+ guidelines = load_prompt_file(lens_prompt_path(lens.prompt_file))
+ for chunk_id in range(1, input.lens_chunk_count + 1):
+ if (lens.pass_number, chunk_id) in done:
+ continue
+ units.append(
+ CoordinatorUnit(
+ task_name=f"{name.replace('-', '_')}_{chunk_id}",
+ pass_number=lens.pass_number,
+ chunk_id=chunk_id,
+ source=lens.source,
+ prompt=_prepare_single_agent_prompt(input, chunk_id, True, guidelines),
+ )
+ )
+ return units
+
+
+@scoped_temporal()
+@close_db_connections
+async def coordinator_review_activity(input: CoordinatorReviewInput) -> CoordinatorReviewResult:
+ """Run the main review and every lens part as sub-agents of one coordinator session (idempotent).
+
+ Each sub-agent's findings persist under the key of its separate session, so dedup reads them the same
+ way. A failed lens sub-agent costs only its own findings. A failed main sub-agent fails the attempt,
+ and the retry runs only the units without a result.
+ """
+ arm = SINGLE_AGENT_FLASH_ARM
+ done = await database_sync_to_async(load_perspective_results, thread_sensitive=False)(
+ team_id=input.team_id,
+ report_id=input.report_id,
+ head_sha=input.head_sha,
+ review_arm=arm,
+ review_design=REVIEW_DESIGN_SINGLE_AGENT,
+ )
+ units = await database_sync_to_async(_coordinator_units, thread_sensitive=False)(input, set(done))
+ if not units:
+ logger.info("Reusing the persisted sub-agent results for this turn")
+ return CoordinatorReviewResult(lens_failures=0)
+ step_name = "flash-coordinator"
+ async with ReviewActivityHeartbeater(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha):
+ try:
+ review = await run_sandbox_review(
+ team_id=input.team_id,
+ user_id=input.user_id,
+ repository=input.repository,
+ branch=input.branch,
+ prompt="",
+ system_prompt=coordinator_prompt(units, model=arm.model, reasoning_effort=arm.reasoning_effort.value),
+ model_to_validate=CoordinatorReview,
+ step_name=step_name,
+ workflow_id_prefix=_sandbox_workflow_id_prefix(step_name),
+ runtime_adapter=arm.runtime_adapter,
+ model=arm.model,
+ reasoning_effort=arm.reasoning_effort,
+ initial_permission_mode=arm.initial_permission_mode,
+ files=[SessionFile(name=unit.file_name, content=unit.prompt) for unit in units],
+ codex_max_subagents=COORDINATOR_MAX_SUBAGENTS,
+ )
+ except AgentTurnFailed as exc:
+ _raise_if_non_retryable_unit_failure(exc)
+ raise
+ reviews = review.reviews_by_task()
+ results = {
+ (unit.pass_number, unit.chunk_id): IssuesReview(
+ issues=issues_from_review(
+ reviews[unit.task_name],
+ pass_number=unit.pass_number,
+ chunk_id=unit.chunk_id,
+ source=unit.source,
+ )
+ )
+ for unit in units
+ if unit.task_name in reviews
+ }
+ logger.info("The coordinator returned %s of %s sub-agent result(s)", len(results), len(units))
+ if results:
+ await database_sync_to_async(persist_perspective_results, thread_sensitive=False)(
+ team_id=input.team_id,
+ report_id=input.report_id,
+ head_sha=input.head_sha,
+ results=results,
+ review_arm=arm,
+ )
+ await _refresh_status_comment(input.team_id, input.report_id, input.review_mode, input.review_design)
+ failed = [unit for unit in units if unit.task_name not in reviews]
+ if any(unit.pass_number == SINGLE_AGENT_PASS_NUMBER for unit in failed):
+ raise ApplicationError("The main review sub-agent failed")
+ return CoordinatorReviewResult(lens_failures=len(failed))
+
+
# --- Combine + scope-clean + dedup -----------------------------------------------------------------
# The reviews API shows this as the finding's validator note, so it says that no validator ran.
@@ -1998,6 +2129,7 @@ def _flash_event_properties(turn: FlashTurnStats | None, sessions: FlashSessionS
"flash_lens_failures": sessions.lens_failures,
"flash_lens_timeouts": sessions.lens_timeouts,
"flash_slowest_session_seconds": sessions.slowest_session_seconds,
+ "flash_coordinator": sessions.coordinator,
}
)
return properties
@@ -2028,6 +2160,7 @@ def _track_review_started(input: TrackReviewStartedInput) -> None:
review_design=input.review_design,
),
"review_design_reason": input.review_design_reason or None,
+ "flash_coordinator": input.coordinator,
**_pr_size_properties(snapshot),
},
groups=groups(team=report.team),
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index 14a50a88667a..fb9ac2b5636e 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -47,6 +47,8 @@ from products.review_hog.backend.reviewer.tools.select_perspectives import Persp
from products.review_hog.backend.temporal.activities import (
AppendCodeReviewArtefactInput,
BuildBodyInput,
+ CoordinatorReviewInput,
+ CoordinatorReviewResult,
DedupResult,
FetchPRDataInput,
FlashSessionStats,
@@ -78,6 +80,7 @@ from products.review_hog.backend.temporal.activities import (
ValidateIntegrationInput,
append_code_review_artefact_activity,
build_body_activity,
+ coordinator_review_activity,
dedup_activity,
fail_status_comment_activity,
fetch_pr_data_activity,
@@ -634,6 +637,7 @@ class ReviewPRWorkflow:
flash_reasoning_effort=acting.flash_reasoning_effort,
review_design=review_design,
review_design_reason=meta.review_design_reason,
+ coordinator=review_design == REVIEW_DESIGN_SINGLE_AGENT and meta.coordinator,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -696,6 +700,7 @@ class ReviewPRWorkflow:
review_mode=inputs.review_mode,
flash_reasoning_effort=acting.flash_reasoning_effort,
review_design=review_design,
+ coordinator=review_design == REVIEW_DESIGN_SINGLE_AGENT and meta.coordinator,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -716,7 +721,14 @@ class ReviewPRWorkflow:
review_design=review_design,
)
- if review_design == REVIEW_DESIGN_SINGLE_AGENT:
+ # The patch keeps a history from before the coordinator existed on separate sessions when it replays.
+ if (
+ review_design == REVIEW_DESIGN_SINGLE_AGENT
+ and workflow.patched("flash-coordinator-2026-10")
+ and meta.coordinator
+ ):
+ flash_sessions = await self._review_with_coordinator(stage, meta.lens_chunk_count)
+ elif review_design == REVIEW_DESIGN_SINGLE_AGENT:
flash_sessions = await self._review_with_single_agent(stage, meta.lens_chunk_count)
else:
await self._review_with_pipeline(stage, acting_user_id)
@@ -1052,6 +1064,37 @@ class ReviewPRWorkflow:
slowest_session_seconds=round(max(session_seconds, default=0.0), 1),
)
+ @staticmethod
+ async def _review_with_coordinator(stage: SandboxStageInput, lens_chunk_count: int) -> FlashSessionStats:
+ """Stages 2 and 3 of the single-agent design, with every session a sub-agent of one coordinator session."""
+ workflow.logger.info(f"STAGE 2-3/7 · Coordinated review: the main review and {lens_chunk_count} lens part(s)")
+ started = workflow.now()
+ result: CoordinatorReviewResult = await workflow.execute_activity(
+ coordinator_review_activity,
+ CoordinatorReviewInput(
+ team_id=stage.team_id,
+ user_id=stage.user_id,
+ report_id=stage.report_id,
+ head_sha=stage.head_sha,
+ repository=stage.repository,
+ branch=stage.branch,
+ run_index=stage.run_index,
+ review_mode=stage.review_mode,
+ flash_reasoning_effort=stage.flash_reasoning_effort,
+ review_design=stage.review_design,
+ lens_chunk_count=lens_chunk_count,
+ ),
+ start_to_close_timeout=_SANDBOX_TIMEOUT,
+ heartbeat_timeout=_SANDBOX_HEARTBEAT,
+ retry_policy=_RETRY,
+ )
+ return FlashSessionStats(
+ lens_failures=result.lens_failures,
+ lens_timeouts=0,
+ slowest_session_seconds=round((workflow.now() - started).total_seconds(), 1),
+ coordinator=True,
+ )
+
@staticmethod
async def _review_with_pipeline(stage: SandboxStageInput, acting_user_id: int) -> None:
"""Stages 2 and 3 of the pipeline design: split into chunks, then the perspective wave."""
diff --git a/products/review_hog/backend/tests/test_feature_flags.py b/products/review_hog/backend/tests/test_feature_flags.py
index 285da23ec2f6..21c3f1f80abb 100644
--- a/products/review_hog/backend/tests/test_feature_flags.py
+++ b/products/review_hog/backend/tests/test_feature_flags.py
@@ -1,9 +1,11 @@
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
+from django.test import SimpleTestCase
+
from parameterized import parameterized
-from products.review_hog.backend.reviewer.feature_flags import flash_pipeline_kill_switch_on
+from products.review_hog.backend.reviewer.feature_flags import flash_pipeline_kill_switch_on, standard_coordinator_on
_FEATURE_ENABLED = "products.review_hog.backend.reviewer.feature_flags.posthoganalytics.feature_enabled"
@@ -22,3 +24,19 @@ class TestFlashPipelineKillSwitch(BaseTest):
) -> None:
with patch(_FEATURE_ENABLED, feature_enabled):
assert flash_pipeline_kill_switch_on(self.team.id) is expected
+
+
+class TestStandardCoordinator(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("flag_on", MagicMock(return_value=True), True),
+ ("flag_error", MagicMock(side_effect=RuntimeError("flag service down")), False),
+ ("flag_unknown", MagicMock(return_value=None), False),
+ ]
+ )
+ def test_coordinator_reads_the_flag_per_pull_request(
+ self, _name: str, feature_enabled: MagicMock, expected: bool
+ ) -> None:
+ with patch(_FEATURE_ENABLED, feature_enabled):
+ assert standard_coordinator_on("posthog/posthog", 42) is expected
+ assert feature_enabled.call_args.args[1] == "posthog/posthog#42"
diff --git a/products/review_hog/backend/tests/test_fetch_review_tier.py b/products/review_hog/backend/tests/test_fetch_review_tier.py
index af935714024c..f637d5fd5c63 100644
--- a/products/review_hog/backend/tests/test_fetch_review_tier.py
+++ b/products/review_hog/backend/tests/test_fetch_review_tier.py
@@ -89,7 +89,14 @@ class TestFetchDecidesTheTier(BaseTest):
expected_status = "closed" if state == "closed" else "idle" if complete or skipped else "active"
assert report.status == expected_status
- @parameterized.expand([("flash", REVIEW_MODE_FLASH, 1), ("full", REVIEW_MODE_FULL, 0)])
+ @parameterized.expand(
+ [
+ ("flash", REVIEW_MODE_FLASH, [10], 1, True),
+ ("flash_two_parts", REVIEW_MODE_FLASH, [600, 600], 2, True),
+ ("full", REVIEW_MODE_FULL, [10], 0, False),
+ ]
+ )
+ @patch(f"{_MODULE}.standard_coordinator_on", return_value=True)
@patch(f"{_MODULE}.flash_pipeline_kill_switch_on", return_value=False)
@patch(f"{_MODULE}._installation_auth", return_value=("tok", None))
@patch(f"{_MODULE}.PRFetcher")
@@ -97,19 +104,25 @@ class TestFetchDecidesTheTier(BaseTest):
self,
_name: str,
review_mode: str,
+ additions: list[int],
expected_parts: int,
+ expected_coordinator: bool,
mock_fetcher: MagicMock,
_auth: MagicMock,
_kill_switch: MagicMock,
+ _coordinator: MagicMock,
) -> None:
# The workflow fans the lens sessions out over this count, so a fetch that leaves it at the
# default runs every Flash turn without its lenses and no error shows it. Only the
# single-agent design fetches test and `.txt` files, so the design must be known first.
# Its prompt reads a left-out diff against the merge base, so the snapshot must keep it.
- pr_file = PRFile(filename="a.py", status="modified", additions=10, deletions=0)
+ pr_files = [
+ PRFile(filename=f"d{index}/a.py", status="modified", additions=count, deletions=0)
+ for index, count in enumerate(additions)
+ ]
merge_base_sha = "f" * 40
mock_fetcher.return_value.fetch_pr_data.return_value = FetchedPR(
- pr_metadata=_pr_metadata(), pr_comments=[], pr_files=[pr_file], diff="", merge_base_sha=merge_base_sha
+ pr_metadata=_pr_metadata(), pr_comments=[], pr_files=pr_files, diff="", merge_base_sha=merge_base_sha
)
meta = _fetch_and_persist(
FetchPRDataInput(
@@ -124,6 +137,7 @@ class TestFetchDecidesTheTier(BaseTest):
)
assert meta.lens_chunk_count == expected_parts
+ assert meta.coordinator is expected_coordinator
single_agent = review_mode == REVIEW_MODE_FLASH
assert mock_fetcher.return_value.fetch_pr_data.call_args.kwargs == {
"review_tests_and_text": single_agent,
diff --git a/products/review_hog/backend/tests/test_fingerprint.py b/products/review_hog/backend/tests/test_fingerprint.py
index 5786b7de56a3..4ffde06a498b 100644
--- a/products/review_hog/backend/tests/test_fingerprint.py
+++ b/products/review_hog/backend/tests/test_fingerprint.py
@@ -62,6 +62,7 @@ class TestRecordTurnMarker(BaseTest):
report_id: str | None = None,
review_mode: str = REVIEW_MODE_FULL,
review_design: str = REVIEW_DESIGN_PIPELINE,
+ coordinator: bool = False,
) -> ReviewHogMarker:
return record_turn_marker(
team_id=team_id or self.team.id,
@@ -72,10 +73,13 @@ class TestRecordTurnMarker(BaseTest):
review_mode=review_mode,
flash_reasoning_effort="medium",
review_design=review_design,
+ coordinator=coordinator,
)
- def _record_single_agent(self, run_index: int) -> ReviewHogMarker:
- return self._record(run_index, review_mode=REVIEW_MODE_FLASH, review_design=REVIEW_DESIGN_SINGLE_AGENT)
+ def _record_single_agent(self, run_index: int, coordinator: bool = False) -> ReviewHogMarker:
+ return self._record(
+ run_index, review_mode=REVIEW_MODE_FLASH, review_design=REVIEW_DESIGN_SINGLE_AGENT, coordinator=coordinator
+ )
def _edit_single_agent_prompt(self, prompt_file: str) -> None:
directory = tempfile.TemporaryDirectory()
@@ -103,6 +107,15 @@ class TestRecordTurnMarker(BaseTest):
assert original.version == "reviewhog-flash-2-2"
assert changed.fingerprint != original.fingerprint
+ def test_the_coordinator_prompt_splits_only_coordinated_cohorts(self) -> None:
+ separate = self._record_single_agent(run_index=1)
+ coordinated = self._record_single_agent(run_index=2, coordinator=True)
+ self._edit_single_agent_prompt("coordinator.md")
+
+ assert coordinated.fingerprint != separate.fingerprint
+ assert self._record_single_agent(run_index=3).fingerprint == separate.fingerprint
+ assert self._record_single_agent(run_index=4, coordinator=True).fingerprint != coordinated.fingerprint
+
@parameterized.expand(
[
(
diff --git a/products/review_hog/backend/tests/test_review_activity.py b/products/review_hog/backend/tests/test_review_activity.py
index 5fa086808b87..83519ff77401 100644
--- a/products/review_hog/backend/tests/test_review_activity.py
+++ b/products/review_hog/backend/tests/test_review_activity.py
@@ -19,6 +19,8 @@ from products.review_hog.backend.reviewer.constants import (
CHUNKING_RUNTIME_ADAPTER,
DEFAULT_REVIEW_ARM,
FLASH_ARM,
+ FLASH_LENS_MAX_CHUNKS,
+ FLASH_LENSES,
REVIEW_HOG_FINDING_MARKER,
REVIEW_MODE_FLASH,
REVIEW_MODE_FULL,
@@ -34,15 +36,18 @@ from products.review_hog.backend.reviewer.models.perspective_selection import (
from products.review_hog.backend.reviewer.models.single_agent_review import SingleAgentFinding, SingleAgentReview
from products.review_hog.backend.reviewer.models.split_pr_into_chunks import Chunk, ChunksList, FileInfo
from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT
+from products.review_hog.backend.reviewer.tools.coordinator_review import CoordinatorResult, CoordinatorReview
from products.review_hog.backend.reviewer.tools.issue_deduplicator import AlreadyRaised, DedupOutcome, Duplicate
from products.review_hog.backend.reviewer.tools.select_perspectives import PerspectiveSelectionDTO
from products.review_hog.backend.temporal.activities import (
+ CoordinatorReviewInput,
LensReviewInput,
LoadedPerspectiveDTO,
ReviewChunkInput,
SandboxStageInput,
SelectPerspectivesInput,
_current_pr_comments,
+ coordinator_review_activity,
dedup_activity,
lens_review_activity,
review_chunk_activity,
@@ -600,6 +605,71 @@ async def test_single_agent_session_persists_mapped_findings_under_the_arm_dedup
]
+ "failed_task,malformed_task,duplicated_task,expect_raise",
+ [
+ ("contracts_security_1", None, None, False),
+ (None, "contracts_security_1", None, False),
+ (None, None, "contracts_security_1", False),
+ ("main_1", None, None, True),
+ ],
+)
+async def test_coordinator_persists_each_sub_agent_under_its_session_key(
+ failed_task: str | None, malformed_task: str | None, duplicated_task: str | None, expect_raise: bool
+) -> None:
+ # Dedup reads each unit by its separate session's key, so a sub-agent stored under another key loses its
+ # findings. The persisted lens part needs no sub-agent again, a malformed lens costs only that lens, and
+ # only a failed main review fails the turn.
+ finding = {"title": "Guard the empty list", "priority": "P1", "file": "a.py", "line_start": 4, "body": "b"}
+ tasks = ["main_1", "performance_reliability_1", "contracts_security_1", "contracts_security_2"]
+ review = CoordinatorReview(
+ results=[
+ CoordinatorResult(
+ task=task,
+ status="failed" if task == failed_task else "ok",
+ findings=[{**finding, "line_start": None} if task == malformed_task else finding],
+ )
+ for task in tasks
+ ]
+ + [CoordinatorResult(task=task, status="ok", findings=[]) for task in tasks if task == duplicated_task]
+ )
+ mock_review = AsyncMock(return_value=review)
+ mock_persist = MagicMock()
+ with (
+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),
+ patch(f"{_MODULE}.load_perspective_results", return_value={(2001, 2): IssuesReview(issues=[])}),
+ patch(f"{_MODULE}._prepare_single_agent_prompt", return_value="prompt"),
+ patch(f"{_MODULE}._refresh_status_comment", AsyncMock()),
+ patch(f"{_MODULE}.persist_perspective_results", mock_persist),
+ patch(f"{_MODULE}.run_sandbox_review", mock_review),
+ ):
+ run = ActivityEnvironment().run(
+ coordinator_review_activity, CoordinatorReviewInput(**_single_agent_stage(lens_chunk_count=2))
+ )
+ if expect_raise:
+ with pytest.raises(ApplicationError, match="main review"):
+ await run
+ else:
+ result = await run
+ assert result.lens_failures == 1
+
+ assert [file.name for file in mock_review.call_args.kwargs["files"]] == [f"{task}.prompt.md" for task in tasks]
+ # Codex rejects spawns past its sub-agent limit, so the limit must fit the largest PR's review units.
+ assert mock_review.call_args.kwargs["codex_max_subagents"] >= 1 + len(FLASH_LENSES) * FLASH_LENS_MAX_CHUNKS
+ persisted = mock_persist.call_args.kwargs["results"]
+ assert {key: review.issues[0].source_perspective for key, review in persisted.items()} == {
+ key: source
+ for key, source, task in [
+ ((2000, 1), "flash-single-agent", "main_1"),
+ ((2001, 1), "flash-lens-performance-reliability", "performance_reliability_1"),
+ ((2002, 1), "flash-lens-contracts-security", "contracts_security_1"),
+ ((2002, 2), "flash-lens-contracts-security", "contracts_security_2"),
+ ]
+ if task not in (failed_task, malformed_task, duplicated_task)
+ }
+
+
def _comment(comment_id: int, line: int | None) -> PRComment:
return PRComment(id=comment_id, path="a.py", line=line, body="x", diff_hunk="", user="other-bot", created_at="c")
diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.py
index 02c9331aabf8..dd59db767624 100644
--- a/products/review_hog/backend/tests/test_temporal_workflow.py
+++ b/products/review_hog/backend/tests/test_temporal_workflow.py
@@ -35,6 +35,8 @@ from products.review_hog.backend.reviewer.tools.single_agent_review import Flash
from products.review_hog.backend.temporal.activities import (
AppendCodeReviewArtefactInput,
BuildBodyInput,
+ CoordinatorReviewInput,
+ CoordinatorReviewResult,
DedupResult,
FetchPRDataInput,
FlashSessionStats,
@@ -152,6 +154,8 @@ async def _run_full_review_pr_workflow(
lens_chunks_capped: bool = False,
fail_lens_units: frozenset[tuple[str, int]] = frozenset(),
fail_main_session: bool = False,
+ coordinator: bool = False,
+ coordinator_lens_failures: int = 0,
automatic_reviewed_head_sha: str | None = None,
skip_agent_review: bool = False,
gate_skips: bool = False,
@@ -200,6 +204,8 @@ async def _run_full_review_pr_workflow(
design_calls: dict[str, set[str]] = {}
single_agent_calls: list[str] = []
lens_calls: list[tuple[str, int]] = []
+ coordinator_calls: list[int] = []
+ started_coordinator: list[bool] = []
lens_timeouts: list[timedelta | None] = []
def _saw_design(stage: str, design: str) -> None:
@@ -230,6 +236,7 @@ async def _run_full_review_pr_workflow(
review_design=review_design,
lens_chunk_count=lens_chunk_count,
lens_chunks_capped=lens_chunks_capped,
+ coordinator=coordinator,
automatic_reviewed_head_sha=automatic_reviewed_head_sha,
skip_agent_review=skip_agent_review,
)
@@ -332,6 +339,11 @@ async def _run_full_review_pr_workflow(
if (input.lens, input.chunk_id) in fail_lens_units:
raise ApplicationError("lens session died", non_retryable=True)
+ @activity.defn(name="coordinator_review_activity")
+ async def coordinator_review(input: CoordinatorReviewInput) -> CoordinatorReviewResult:
+ coordinator_calls.append(input.lens_chunk_count)
+ return CoordinatorReviewResult(lens_failures=coordinator_lens_failures)
+
@activity.defn(name="dedup_activity")
async def dedup(input: SandboxStageInput) -> DedupResult:
_saw_design("dedup", input.review_design)
@@ -423,6 +435,7 @@ async def _run_full_review_pr_workflow(
effort_calls.setdefault("track", set()).add(input.flash_reasoning_effort)
_saw_mode("track", input.review_mode)
track_started_calls.append((input.run_index, input.turn_trigger_source))
+ started_coordinator.append(input.coordinator)
_saw_design("track", input.review_design)
return None
@@ -454,6 +467,7 @@ async def _run_full_review_pr_workflow(
review,
single_agent_review,
lens_review,
+ coordinator_review,
dedup,
load_validation,
validate_chunk,
@@ -533,6 +547,8 @@ async def _run_full_review_pr_workflow(
"single_agent": single_agent_calls,
"lens": lens_calls,
"lens_timeouts": lens_timeouts,
+ "coordinator": coordinator_calls,
+ "started_coordinator": started_coordinator,
"gate": gate_calls,
"status_posts": status_posts,
}
@@ -742,6 +758,33 @@ async def test_review_pr_workflow_single_agent_design_replaces_chunking_review_a
assert recorded["designs"] == {stage: {"single_agent"} for stage in ("dedup", "track")}
[email protected]("review_design,expect_coordinator", [("single_agent", True), ("pipeline", False)])
+async def test_review_pr_workflow_coordinator_replaces_the_separate_sessions_of_a_single_agent_turn(
+ review_design: str, expect_coordinator: bool
+) -> None:
+ # The fetch records the flag for every turn, so a pipeline turn must ignore it. A coordinated turn must
+ # run no separate sessions, and its events must say it ran coordinated, or the rollout cannot be compared.
+ recorded = await _run_full_review_pr_workflow(
+ publish=True,
+ review_mode="flash",
+ review_design=review_design,
+ lens_chunk_count=2,
+ coordinator=True,
+ coordinator_lens_failures=1,
+ )
+
+ assert recorded["coordinator"] == ([2] if expect_coordinator else [])
+ assert recorded["started_coordinator"] == [expect_coordinator]
+ assert recorded["publish"] == [7]
+ if expect_coordinator:
+ assert recorded["single_agent"] == []
+ assert recorded["lens"] == []
+ [(_, sessions)] = recorded["track_flash"]
+ assert sessions is not None
+ assert (sessions.lens_failures, sessions.coordinator) == (1, True)
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"fail_lens_units,fail_main_session,expect_failed",