: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(review-hog): keep long-running reviews visible (#110239)
Alex Lebedevdff50fdafec7
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex 51ff3c632686..25ceb720d7c2 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -300,6 +300,8 @@ An active turn keeps its settings snapshot, and an existing report's status commIf a review fails, the next attempt keeps cached reviewer results for the same commit, model, and reasoning effort.Deduplication retires superseded findings from the unfinished turn and reuses a verdict only when its finding, commit, review mode, and model configurations are unchanged.Completed turns remain in the report history.+Long-running review activities refresh the active report every minute so it remains visible in Code review while an agent works without new results.+The refresh stops when the activity exits; a report with no new activity still expires from the running list after 30 minutes.Review-started, completed, and failed event IDs distinguish Full and Flash retries while preserving the legacy Full IDs.When calculating completion rates, match report, turn, and mode, treating an absent mode as Full for legacy events.Flash finding-outcome events use the model configuration saved with the finding, even if the Flash defaults change before classification.diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex c1ef9d42b89c..9931542f3cd2 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -752,6 +752,13 @@ list — every 10s while a run is in progress or freshly triggered, every 30s ottabs with an immediate refresh on tab return — and a poll response that shows a run finishing alsorefreshes the perspective stats and an open drawer's detail (`reviewHogSettingsLogic`).+An active review stays visible while its report or working artefacts have activity within `IN_PROGRESS_STALE_AFTER` (30 minutes).+Long-running chunking, selection, review, deduplication, and validation activities also refresh `ReviewReport.updated_at` every minute, so an agent can keep working without producing an artefact during that window.+Each refresh is scoped to the team, report, active status, and reviewed commit.+These refreshes stop when the activity exits, and stale reviews still expire after the same quiet window.+Temporal heartbeats continue independently of the database refresh.+The list selects running candidates by their latest report update, so newer stale runs cannot push a live run off the page.+---## Known issues & tech debtdiff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.pyindex 09de6cbd5b3d..02383494e4cf 100644--- a/products/review_hog/backend/api/reviews.py+++ b/products/review_hog/backend/api/reviews.py@@ -403,8 +403,8 @@ def _fetch_pr_metadata(github: GitHubIntegration, owner: str, repo: str, pr_numbdef _in_progress_report_ids(team_id: int, reports: list[ReviewReport]) -> set[str]:"""Which ACTIVE reports are visibly running: artefact or report activity within the staleness window.- Artefacts stream in throughout a run (snapshot, chunk set, per-chunk results, verdicts), so the- newest artefact is the liveness signal; a crashed run goes quiet and ages out instead of showing+ Artefacts mark persisted progress, and long review activities refresh the report timestamp while+ their sandbox runs. Both stop when a worker dies, so a crashed run ages out instead of showinga stuck spinner forever.`finding_outcome` is excluded because it is the one artefact type not written by a turn: the@@ -592,9 +592,11 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetprobe_limit = limit + 1team_id, queryset = self._reports(request, scope=params.validated_data["scope"])completed = list(queryset.filter(last_run_at__isnull=False).order_by("-last_run_at")[:probe_limit])- # First-turn runs have no completed turn yet; they only surface while visibly running.+ # First-turn runs have no completed turn yet; they only surface while visibly running. A crashed+ # run stays ACTIVE, so rank by report activity: ranked by creation, newer crashed runs fill the+ # slice and hide an older live run.running_first_turn = list(- queryset.filter(status=ReviewReport.Status.ACTIVE, last_run_at__isnull=True).order_by("-created_at")[+ queryset.filter(status=ReviewReport.Status.ACTIVE, last_run_at__isnull=True).order_by("-updated_at")[:probe_limit])diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.pyindex 157b5b89423a..c40c25f02f4a 100644--- a/products/review_hog/backend/reviewer/progress.py+++ b/products/review_hog/backend/reviewer/progress.py@@ -42,9 +42,8 @@ logger = logging.getLogger(__name__)REVIEW_STAGES = ["fetching", "chunking", "selecting", "reviewing", "deduplicating", "validating", "finalizing"]-# An ACTIVE report only counts as running while its run is visibly moving (artefacts stream in-# throughout a run); past this quiet window a review run stops rendering as live, and a resolution-# run with no closing note starts rendering as died partway.+# Artefacts and activity heartbeats keep active reviews fresh; stopped runs must age out so the UI+# does not show a live spinner forever. A resolution run with no closing note then reads as stopped.IN_PROGRESS_STALE_AFTER = timedelta(minutes=30)RESOLUTION_RESOLVING = "resolving"diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 24208446df1a..6087b63a0713 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -9,7 +9,7 @@ respected and the sandbox fan-out stays by-reference.Sandbox-turn activities (chunk / review / dedup) call `run_sandbox_review`, which spins a single-turnagent (minutes); `validate_chunk_activity` instead drives one warm multi-turn session per chunk. Both-take minutes, so they declare a `heartbeat_timeout` on dispatch and heartbeat via `Heartbeater()`. ORM+take minutes, so they declare a `heartbeat_timeout` on dispatch and heartbeat via `ReviewActivityHeartbeater`. ORMaccess goes through `database_sync_to_async(..., thread_sensitive=False)`; `@scoped_temporal()` +`@close_db_connections` mirror the Signals report activities."""@@ -29,7 +29,6 @@ from posthog.event_usage import groupsfrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.team.team import Teamfrom posthog.sync import database_sync_to_async-from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections@@ -138,6 +137,7 @@ from products.review_hog.backend.reviewer.tools.split_pr_into_chunks import (plan_deterministic_chunks,reconcile_chunks,)+from products.review_hog.backend.temporal.heartbeat import ReviewActivityHeartbeaterfrom products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC, TRIGGER_LABEL, TRIGGER_MANUALfrom products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.signals.backend.artefact_schemas import CodeReview, CodeReviewCounts@@ -860,7 +860,7 @@ async def split_chunks_activity(input: SandboxStageInput) -> list[int]:# shot keeps the agentic sandbox, which can navigate the repo instead of holding it all at once.additions = count_reviewable_additions(snapshot.pr_files)use_oneshot = bool(CHUNKING_ONESHOT_MAX_ADDITIONS) and additions <= CHUNKING_ONESHOT_MAX_ADDITIONS- async with Heartbeater():+ async with ReviewActivityHeartbeater(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha):if use_oneshot:chunks = await run_oneshot_review(team_id=input.team_id,@@ -944,7 +944,7 @@ async def select_perspectives_activity(input: SelectPerspectivesInput) -> Perspeif not chunks.chunks:return Noneprompt = generate_selection_prompt(snapshot.pr_metadata, chunks.chunks, snapshot.pr_files, input.perspectives)- async with Heartbeater():+ async with ReviewActivityHeartbeater(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha):raw = await run_oneshot_review(team_id=input.team_id,user_id=input.user_id,@@ -1062,7 +1062,7 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:if input.blind_spot_checkelse f"issues-review-p{input.pass_number}-c{input.chunk_id}")- async with Heartbeater():+ async with ReviewActivityHeartbeater(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha):review = await run_sandbox_review(team_id=input.team_id,user_id=input.user_id,@@ -1138,7 +1138,7 @@ async def dedup_activity(input: SandboxStageInput) -> DedupResult:prior_findings = await database_sync_to_async(load_prior_findings_with_verdicts, thread_sensitive=False)(team_id=input.team_id, report_id=input.report_id, before_run_index=input.run_index)- async with Heartbeater():+ async with ReviewActivityHeartbeater(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha):survivors = await deduplicate_issues(team_id=input.team_id,user_id=input.user_id,@@ -1232,7 +1232,7 @@ async def validate_chunk_activity(input: ValidateChunkInput) -> ValidateChunkRessession: MultiTurnSession | None = Nonechunk_ok = Falsetry:- async with Heartbeater():+ async with ReviewActivityHeartbeater(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha):for issue in pending:issue_files = [f for f in pr_files if f.filename == issue.file]try:diff --git a/products/review_hog/backend/temporal/heartbeat.py b/products/review_hog/backend/temporal/heartbeat.pynew file mode 100644index 000000000000..65c23be1ba48--- /dev/null+++ b/products/review_hog/backend/temporal/heartbeat.py@@ -0,0 +1,61 @@+import asyncio+import logging+from contextlib import suppress+from datetime import timedelta+from typing import TYPE_CHECKING++from django.utils import timezone++from posthog.sync import database_sync_to_async+from posthog.temporal.common.heartbeat import Heartbeater++from products.review_hog.backend.models import ReviewReport++if TYPE_CHECKING:+ from types import TracebackType++logger = logging.getLogger(__name__)++REPORT_HEARTBEAT_INTERVAL = timedelta(minutes=1)+++class ReviewActivityHeartbeater(Heartbeater):+ def __init__(self, *, team_id: int, report_id: str, head_sha: str) -> None:+ super().__init__()+ self.team_id = team_id+ self.report_id = report_id+ self.head_sha = head_sha+ self.report_heartbeat_task: asyncio.Task[None] | None = None++ def touch_report(self) -> None:+ now = timezone.now()+ ReviewReport.objects.for_team(self.team_id).filter(+ id=self.report_id,+ status=ReviewReport.Status.ACTIVE,+ head_sha=self.head_sha,+ updated_at__lt=now - REPORT_HEARTBEAT_INTERVAL,+ ).update(updated_at=now)++ async def _heartbeat_report(self) -> None:+ while True:+ try:+ await database_sync_to_async(self.touch_report, thread_sensitive=False)()+ except Exception:+ logger.exception("Could not refresh ReviewHog report activity for %s", self.report_id)+ await asyncio.sleep(REPORT_HEARTBEAT_INTERVAL.total_seconds())++ async def __aenter__(self) -> "ReviewActivityHeartbeater":+ await super().__aenter__()+ # Temporal heartbeats cannot keep the reviews API fresh while a sandbox has no results yet.+ self.report_heartbeat_task = asyncio.create_task(self._heartbeat_report())+ return self++ async def __aexit__(+ self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: "TracebackType | None"+ ) -> None:+ if self.report_heartbeat_task is not None:+ self.report_heartbeat_task.cancel()+ with suppress(asyncio.CancelledError):+ await self.report_heartbeat_task+ self.report_heartbeat_task = None+ await super().__aexit__(exc_type, exc, traceback)diff --git a/products/review_hog/backend/tests/test_review_activity.py b/products/review_hog/backend/tests/test_review_activity.pyindex 6c144ba6aab0..fef9fbf8fb48 100644--- a/products/review_hog/backend/tests/test_review_activity.py+++ b/products/review_hog/backend/tests/test_review_activity.py@@ -1,3 +1,5 @@+import asyncio+from contextlib import suppressfrom dataclasses import replaceimport pytest@@ -33,9 +35,11 @@ from products.review_hog.backend.temporal.activities import (select_perspectives_activity,split_chunks_activity,)+from products.review_hog.backend.temporal.heartbeat import REPORT_HEARTBEAT_INTERVAL, ReviewActivityHeartbeaterfrom products.tasks.backend.facade.run_config import ReasoningEffort, RuntimeAdapter_MODULE = "products.review_hog.backend.temporal.activities"+_HEARTBEAT_MODULE = "products.review_hog.backend.temporal.heartbeat"def _review_input(**overrides: object) -> ReviewChunkInput:@@ -91,6 +95,71 @@ def _snapshot(pr_files: list[PRFile] | None = None) -> PRSnapshotArtefact:)[email protected]("outcome", ["completed", "failed", "cancelled"])+async def test_activity_report_heartbeat_repeats_and_stops_with_the_activity(outcome: str) -> None:+ pulses: asyncio.Queue[None] = asyncio.Queue()+ timers: asyncio.Queue[asyncio.Future[None]] = asyncio.Queue()+ finish = asyncio.Event()+ attempts = 0++ async def refresh_report() -> None:+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise RuntimeError("database unavailable")+ await pulses.put(None)++ async def advanceable_sleep(delay: float) -> None:+ assert delay == REPORT_HEARTBEAT_INTERVAL.total_seconds()+ timer = asyncio.get_running_loop().create_future()+ await timers.put(timer)+ await timer++ async def run_activity() -> None:+ async with ReviewActivityHeartbeater(team_id=1, report_id="report", head_sha="head"):+ await finish.wait()+ if outcome == "failed":+ raise RuntimeError("review failed")++ with (+ patch(f"{_HEARTBEAT_MODULE}.Heartbeater.__aenter__", new=AsyncMock()),+ patch(f"{_HEARTBEAT_MODULE}.Heartbeater.__aexit__", new=AsyncMock()),+ patch(f"{_HEARTBEAT_MODULE}.database_sync_to_async", return_value=refresh_report),+ patch(f"{_HEARTBEAT_MODULE}.asyncio.sleep", side_effect=advanceable_sleep),+ ):+ task = asyncio.create_task(run_activity())+ try:+ async with asyncio.timeout(10):+ first_timer = await timers.get()+ first_timer.set_result(None)+ await pulses.get()+ second_timer = await timers.get()+ second_timer.set_result(None)+ await pulses.get()+ last_timer = await timers.get()++ if outcome == "cancelled":+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ elif outcome == "failed":+ finish.set()+ with pytest.raises(RuntimeError, match="review failed"):+ await task+ else:+ finish.set()+ await task++ assert attempts == 3+ assert last_timer.cancelled()+ assert pulses.empty()+ finally:+ task.cancel()+ with suppress(asyncio.CancelledError, RuntimeError):+ await task++@pytest.mark.asyncio@pytest.mark.parametrize("additions,expects_oneshot",@@ -107,7 +176,7 @@ async def test_split_chunks_activity_routes_llm_chunking_by_oneshot_gate(additiomock_oneshot = AsyncMock(return_value=plan)mock_sandbox = AsyncMock(return_value=plan)with (- patch(f"{_MODULE}.Heartbeater"),+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),patch(f"{_MODULE}.load_chunk_set", return_value=None),patch(f"{_MODULE}.load_pr_snapshot",@@ -158,7 +227,7 @@ async def test_review_chunk_activity_flash_turn_runs_on_the_flash_arm_and_stampsmock_prepare = MagicMock(return_value="review-prompt")env = ActivityEnvironment()with (- patch(f"{_MODULE}.Heartbeater"),+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),patch(f"{_MODULE}._prepare_review_prompt", mock_prepare),patch(f"{_MODULE}.load_review_arm", return_value=DEFAULT_REVIEW_ARM),patch(f"{_MODULE}.persist_perspective_results", mock_persist),@@ -210,7 +279,7 @@ async def test_review_chunk_activity_runs_on_the_reports_persisted_arm() -> Nonemock_prepare = MagicMock(return_value="review-prompt")env = ActivityEnvironment()with (- patch(f"{_MODULE}.Heartbeater"),+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),patch(f"{_MODULE}._prepare_review_prompt", mock_prepare),patch(f"{_MODULE}.load_review_arm", return_value=arm),patch(f"{_MODULE}.persist_perspective_results"),@@ -242,7 +311,7 @@ async def test_blind_spot_unit_scopes_wave_findings_to_its_chunk_and_steps_as_bl}mock_review = AsyncMock(return_value=IssuesReview(issues=[]))with (- patch(f"{_MODULE}.Heartbeater"),+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),patch(f"{_MODULE}.load_review_arm", return_value=DEFAULT_REVIEW_ARM),patch(f"{_MODULE}.load_perspective_results", return_value=done),patch(f"{_MODULE}.load_pr_snapshot", return_value=_snapshot()),@@ -311,7 +380,7 @@ async def test_select_perspectives_activity_persists_the_normalized_plan() -> Nomock_oneshot = AsyncMock(return_value=raw)mock_persist = MagicMock()with (- patch(f"{_MODULE}.Heartbeater"),+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),patch(f"{_MODULE}.load_perspective_selection", return_value=None),patch(f"{_MODULE}.load_pr_snapshot", return_value=_snapshot()),patch(diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.pyindex a34ee9de6bc9..97c83f70d0fa 100644--- a/products/review_hog/backend/tests/test_reviews_api.py+++ b/products/review_hog/backend/tests/test_reviews_api.py@@ -35,6 +35,7 @@ from products.review_hog.backend.reviewer.persistence import (persist_pr_snapshot,)from products.review_hog.backend.reviewer.progress import RESOLUTION_RUN_NOTE_AUTHOR+from products.review_hog.backend.temporal.heartbeat import ReviewActivityHeartbeaterfrom products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.signals.backend.artefact_schemas import NoteArtefact@@ -504,6 +505,61 @@ class TestRecentReviewsAPI(APIBaseTest):"total": 2,}+ @parameterized.expand(+ [+ ("active", "sha1", False, True),+ ("idle", "sha1", False, False),+ ("active", "another-head", False, False),+ ("active", "sha1", True, False),+ ]+ )+ def test_activity_heartbeat_keeps_only_its_active_review_visible(+ self, status: str, heartbeat_head: str, another_team: bool, visible: bool+ ) -> None:+ now = timezone.now()+ with time_machine.travel(now - IN_PROGRESS_STALE_AFTER - timedelta(minutes=1), tick=False):+ running = self._report(+ pr_number=2, acting_user=self.user, completed=False, run_count=0, head_sha="sha1", status=status+ )+ heartbeat_team_id = self.team.id+ if another_team:+ heartbeat_team_id = Team.objects.create(organization=self.organization, name="another project").id+ heartbeat = ReviewActivityHeartbeater(+ team_id=heartbeat_team_id, report_id=str(running.id), head_sha=heartbeat_head+ )++ with time_machine.travel(now, tick=False):+ assert self.client.get(self.url).json()["results"] == []+ before_pulse = running.updated_at+ heartbeat.touch_report()+ running.refresh_from_db()+ assert running.updated_at == (now if visible else before_pulse)+ rows = self.client.get(self.url).json()["results"]+ assert bool(rows) is visible+ if visible:+ assert rows[0]["pr_number"] == 2+ assert rows[0]["in_progress"] is True+ assert rows[0]["run_count"] == 0++ with time_machine.travel(now + IN_PROGRESS_STALE_AFTER + timedelta(seconds=1), tick=False):+ assert self.client.get(self.url).json()["results"] == []++ def test_heartbeating_first_turn_outranks_newer_stale_first_turns(self) -> None:+ # Crashed first turns stay ACTIVE. More of them than the probe slice, all newer than a live+ # run, must not push that live run out of the list.+ now = timezone.now()+ with time_machine.travel(now - timedelta(hours=2), tick=False):+ live = self._report(pr_number=1, acting_user=self.user, completed=False, run_count=0, head_sha="sha1")+ with time_machine.travel(now - IN_PROGRESS_STALE_AFTER - timedelta(minutes=1), tick=False):+ for pr_number in range(2, 5):+ self._report(pr_number=pr_number, acting_user=self.user, completed=False, run_count=0)++ with time_machine.travel(now, tick=False):+ ReviewActivityHeartbeater(team_id=self.team.id, report_id=str(live.id), head_sha="sha1").touch_report()+ rows = self.client.get(self.url, {"limit": 1}).json()["results"]++ assert [(row["pr_number"], row["in_progress"]) for row in rows] == [(1, True)]+def _resolution_run(self, report: ReviewReport, thread_ids: list[str], *, skipped: int = 0) -> None:ReviewReportArtefact.append_resolution_run(team_id=self.team.id,diff --git a/products/review_hog/backend/tests/test_validate_activity.py b/products/review_hog/backend/tests/test_validate_activity.pyindex aafea3a112e3..3d0596d7943b 100644--- a/products/review_hog/backend/tests/test_validate_activity.py+++ b/products/review_hog/backend/tests/test_validate_activity.py@@ -94,7 +94,7 @@ def _chunk_context(issues: list[Issue], done: dict[str, IssueValidation]) -> Ite# The activity receives only issue ids and reloads content from the finding rows — the loader# is patched to hand back the live issues the test built.with (- patch(f"{_MODULE}.Heartbeater"),+ patch(f"{_MODULE}.ReviewActivityHeartbeater"),patch(f"{_MODULE}.load_run_issues", return_value=issues),patch(f"{_MODULE}.load_run_validations", return_value=done),patch(f"{_MODULE}.load_pr_snapshot", return_value=_snapshot()),