: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 code review statuses live without a refresh (#82601)
Alex Lebedev37f539ab4dae
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex cb39cdc85fbf..a1fd136ccba6 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -287,7 +287,12 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /no chunk walk, no file inventory, no summary of the diff, because nobody reads one. Valid `MUST_FIX`/`SHOULD_FIX`findings whose line isn't on the diff are still appended as an **"Other findings (outside the changed lines)"**section so they aren't silently dropped at publish.- `finalize_review_report` stores it as `ReviewReport.report_markdown` and bumps the run watermark.+ `finalize_review_report` stores it as `ReviewReport.report_markdown` and bumps the run watermark. On+ publishing runs it **defers the idle write** to the publish stage — the report stays `active` through+ stage 10, `publish_persisted_review` returns it to `idle` on every outcome, and the failure activity+ restores rest on a dead run — so the reviews API never reports a completed-but-unpublished turn as at+ rest (the UI's poll would stop on that snapshot and freeze a wrong "Not published"). Non-publishing+ runs go `idle` at finalize; `progress_payload` labels the deferred window "finalizing".10. **Publish** — `publish_review` (GitHub REST via the gated egress transport, **DB-driven**) reads the body from`ReviewReport.report_markdown` and the inline comments from the valid finding/verdict rows (`load_valid_findings`),posts a standalone "ReviewHog Alpha 🦔" feedback comment, then a PR review (`event="COMMENT"`, **pinned to the@@ -592,7 +597,10 @@ project-wide so any listed review opens. A specific report is linkable at `/codetargets it, so the param is a permanent contract). The drawer buckets a review's findings into published vsbelow-threshold by the detail's stored `run_urgency_threshold` — the viewer's current setting is only thefallback for pre-column rows — and its first tab reads "Published" only when the review actually posted-(`published_head_sha` set), "Kept" otherwise.+(`published_head_sha` set), "Kept" otherwise. The scene keeps itself current by polling the reviews+list — every 10s while a run is in progress or freshly triggered, every 30s otherwise, paused on hidden+tabs with an immediate refresh on tab return — and a poll response that shows a run finishing also+refreshes the perspective stats and an open drawer's detail (`reviewHogSettingsLogic`).---@@ -628,6 +636,10 @@ fallback for pre-column rows — and its first tab reads "Published" only when t"Published" with no not-published banner. Fix: `retrieve` already loads the completed head — exposeper-turn truth (`published_head_sha == completed_head_sha`) on the detail payload and gate the drawer'spublished flag on it.+- **TODO — no resolution-stage progress label.** A resolution run holds the report `active` at a+ published head, where `progress_payload` falls through to a review-stage label ("deduplicating"; the+ pre-publish window reads "finalizing"). A dedicated `resolving` stage needs the serializer enum, the+ frontend stage labels, and regenerated types — deliberately left out of the staleness fix.- **Alpha maturity** — the published comment still says "ReviewHog Alpha" and asks users to reply"valid"/"invalid" (`reviewer/tools/publish_review.py`, the `post_promo` block). Publish is now liveper-run (the trigger endpoint posts with `publish=true`), so settle the prod wording before real usersdiff --git a/products/review_hog/CONTEXT.md b/products/review_hog/CONTEXT.mdindex 57f7df6b35e8..6ada5466e7a5 100644--- a/products/review_hog/CONTEXT.md+++ b/products/review_hog/CONTEXT.md@@ -8,6 +8,7 @@ Vocabulary settled while working on the product. Pure vocabulary — no spec, no- **Pipeline payload** — the same finding/verdict fields as consumed by downstream LLM stages (validator, dedup, covered-findings). The quality-critical audience.- **Structural conciseness vs compression** — _structural_: the same information content reshaped into labeled bullets (claim / trigger / evidence / impact); _compression_: dropping information to save words. The no-quality-loss constraint rules out compression of pipeline payloads; it does not rule out restructuring.- **Verify, don't restate** — the rule for validator argumentation: it is the _verification delta_ (what was checked, what was found with file:line evidence, confirmed impact, priority rationale), never a restatement of the finding body's claim. Safe because the full body always travels with the argumentation — every consumer, human or LLM, receives both in the same comment or payload.+- **Report status (`active` / `idle` / `closed`)** — the report-level at-work flag: `active` while any run (a review turn or a resolution run) is working the report, `idle` at rest, `closed` retired. A publishing turn holds `active` through the GitHub publish, so `idle` always implies the published state is final. The UI reads a row as in-progress from `active` plus recent activity, so a crashed run ages out of view instead of reading as running forever.## Resolution stage (the "implement the fixes" flow)diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.mdindex 546d38b36b3b..f8952687f56f 100644--- a/products/review_hog/DECISIONS.md+++ b/products/review_hog/DECISIONS.md@@ -3149,6 +3149,46 @@ RATE_LIMITED` (GraphQL's primary signal, invisible to the REST-shaped helper) no---+### 🧯 Live statuses in the Code review UI — baseline polling + idle deferred to publish (BUILT 2026-08-13)++The Code review scene went stale without a manual refresh, three ways, all rooted in the list poll arming only+while an in-progress row was already visible: externally-triggered runs (label / inbox / MCP / a teammate) never+appeared on an already-open page; the run-end race froze rows on "Not published" (finalize wrote `idle` before the+publish stage wrote `published_head_sha`, and a poll tick landing in that window was the poll's last — it disposes+itself at the first at-rest response); and the stats cards and an open drawer never refreshed at all.++**Decisions (and the alternatives weighed):**++- **The poll never stops; it changes cadence.** 10s while a run is in progress or freshly triggered, 30s idle,+ paused on hidden tabs (the disposables plugin), one immediate refresh on tab return (a non-pausing+ `visibilitychange` listener — a pausing one would be re-attached mid-dispatch of the very event it must observe,+ and listeners added during dispatch don't run for that event). Rejected: stop-after-N-idle (a state machine to+ save a flag-gated dogfood page a 30s request) and a push channel (nothing else on the scene justifies the+ infrastructure).+- **Finalize defers the idle write on publishing runs** (`will_publish` on `BuildBodyInput` →+ `finalize_review_report`); `publish_persisted_review` returns the report to `idle` on every outcome (posted — in+ the same save as the watermark —, already-posted skip, and no-post), and `fail_status_comment_activity` restores+ rest on a dead run. The failure-path write lives inside that existing activity, not as a new workflow command,+ because a new unconditional command breaks replay for in-flight histories. Rejected: a `publishing` status enum+ value (a migration plus every status reader, for a state that lasts seconds) and a frontend-only reconciliation+ delay (leaves the API reporting `in_progress=false, published=false` for a state that is neither).+- **The publish window reads "finalizing".** With `run_count` already bumped there are no in-flight findings, so+ `progress_payload` otherwise falls through and misreads the finished turn's working state as "deduplicating".+ The branch is scoped to the not-yet-published head deliberately: a resolution run holds the same+ ACTIVE-at-completed-head shape at a _published_ head and keeps its pre-existing label — the proper `resolving`+ stage (serializer enum + frontend labels + regenerated types) is a separate change, in flight on its own+ (maintainer, 2026-08-13), tracked in ARCHITECTURE.md's known issues.+- **A poll response is the fan-out point.** A run observed finishing (its `in_progress` dropping or `run_count`+ bumping between responses) reloads the perspective stats, and the drawer's detail when it is open on that+ report. The error banner keys off a new `markInitialLoadFailed` (dispatched only when the failing surface has+ nothing loaded), so a background poll blip retries silently instead of flashing the page-level failure banner.++Known residuals, deliberate: the list's `published` flag is still report-lifetime (the drawer-flag TODO in+ARCHITECTURE.md's known issues), and `_in_progress_report_ids`' 30-minute staleness cutoff can still hide a run+whose current stage stays quiet longer than that.++---+### 🔮 Future directions (product, post-Stage-5 — not scheduled)#### Adversarial validation — a 3-skeptic panel instead of a single verify pass (noted 2026-07-03)diff --git a/products/review_hog/backend/reviewer/persistence.py b/products/review_hog/backend/reviewer/persistence.pyindex de6af630b262..87e1fc6a188c 100644--- a/products/review_hog/backend/reviewer/persistence.py+++ b/products/review_hog/backend/reviewer/persistence.py@@ -673,6 +673,7 @@ def finalize_review_report(run_index: int,head_sha: str,urgency_threshold: str | None = None,+ will_publish: bool = False,) -> None:"""Mark the turn complete: store the body, bump `run_count`, stamp `last_run_at` and the reviewed head.@@ -684,15 +685,24 @@ def finalize_review_report(`urgency_threshold` is the resolve snapshot the turn's body/publish gated on — stamped HERE, notat resolve (which describes the *next* turn and would drift mid re-review under a differentacting user), so the detail view buckets published vs held-back findings by the gate that ran.++ `will_publish` defers the idle write to the publish stage. The reviews API reads ACTIVE as+ in-progress, so going idle here, seconds before `published_head_sha` lands, hands the UI's+ poll a completed-but-unpublished row as the run's final state, and the poll stops on it with a+ wrong "Not published" frozen on screen. The publish path returns the report to IDLE on every+ outcome (`publish_persisted_review`), and the workflow's failure activity covers a publish that+ dies past retries."""- ReviewReport.objects.for_team(team_id).filter(id=report_id, run_count=run_index - 1).update(- report_markdown=body_markdown,- run_count=run_index,- last_run_at=timezone.now(),- completed_head_sha=head_sha,- run_urgency_threshold=urgency_threshold,- status=ReviewReport.Status.IDLE,- )+ updates: dict[str, object] = {+ "report_markdown": body_markdown,+ "run_count": run_index,+ "last_run_at": timezone.now(),+ "completed_head_sha": head_sha,+ "run_urgency_threshold": urgency_threshold,+ }+ if not will_publish:+ updates["status"] = ReviewReport.Status.IDLE+ ReviewReport.objects.for_team(team_id).filter(id=report_id, run_count=run_index - 1).update(**updates)def _issue_key(issue: Issue, run_index: int) -> str:diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.pyindex 9cf36cee6159..b951f6f546cb 100644--- a/products/review_hog/backend/reviewer/progress.py+++ b/products/review_hog/backend/reviewer/progress.py@@ -246,6 +246,19 @@ def progress_payload(if judged >= len(current_pairs):return {"review_stage": "finalizing", "done": judged, "total": len(current_pairs)}return {"review_stage": "validating", "done": judged, "total": len(current_pairs)}+ # The publish window: on publishing runs finalize defers the idle write to the publish stage,+ # so the report is still ACTIVE with `run_count` already bumped and no in-flight findings, and+ # the branches below would misread the finished turn's working state as "deduplicating".+ # Scoped to the not-yet-published head so a resolution run's ACTIVE window (published head)+ # keeps its current label; relabeling that window properly is its own change. Trade-off: an+ # unpublished same-head re-run reads "finalizing" until dedup persists its first findings,+ # a brief stretch because such a turn resumes its chunk and perspective state.+ if (+ report.completed_head_sha+ and report.completed_head_sha == report.head_sha+ and report.published_head_sha != report.head_sha+ ):+ return {"review_stage": "finalizing", "done": None, "total": None}if turn.chunk_count is not None:done = turn.perspective_reads or 0# The selector runs between chunking and the fan-out; its persisted plan is the stage marker.diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.pyindex e77617781df9..7e86f1f23867 100644--- a/products/review_hog/backend/reviewer/tools/publish_review.py+++ b/products/review_hog/backend/reviewer/tools/publish_review.py@@ -46,6 +46,14 @@ class PublishOutcome:review_url: str | None = None+def _mark_report_idle(team_id: int, report_id: str) -> None:+ """Return the report to rest. Publishing runs defer finalize's idle write to this stage, and+ the reviews API reads ACTIVE as in-progress, so every publish outcome (posted, already-posted+ skip, nothing publishable) must end with the report IDLE or the UI shows a finished run as+ running until the staleness cutoff."""+ ReviewReport.objects.for_team(team_id).filter(id=report_id).update(status=ReviewReport.Status.IDLE)++def publish_persisted_review(*,team_id: int,@@ -75,6 +83,7 @@ def publish_persisted_review(report = ReviewReport.objects.for_team(team_id).get(id=report_id)if report.published_head_sha == head_sha:logger.info(f"Review for {owner}/{repo}#{pr_number} already published at {head_sha}; skipping")+ _mark_report_idle(team_id, report_id)return PublishOutcome(posted=False)snapshot = load_pr_snapshot(team_id=team_id, report_id=report_id, head_sha=head_sha)pr_files = snapshot.pr_files if snapshot is not None else []@@ -116,14 +125,20 @@ def publish_persisted_review(# The base a later sweep compares this turn's findings against. Without it every finding is# compared from the newest publish, so a fix landing between two turns falls outside the diff.report.published_head_shas = {**(report.published_head_shas or {}), str(run_index): head_sha}+ # Idle lands in the same save as the watermark, so no reader can see the published head+ # with the report still counting as in-progress.+ report.status = ReviewReport.Status.IDLEreport.save(update_fields=["published_head_sha","published_urgency_thresholds","published_head_shas",+ "status","updated_at",])+ else:+ _mark_report_idle(team_id, report_id)return outcomediff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 93a71ed4572c..b3baec1b9d31 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -349,6 +349,10 @@ class BuildBodyInput:# The acting user's threshold, snapshotted at resolve time. Defaulted so pre-field payloads# still deserialize — a missing field takes the current default, not the run's original gate.urgency_threshold: str = IssuePriority.CONSIDER.value+ # Whether this run dispatches the publish stage after finalizing. Publishing runs defer the+ # idle write to publish so the report never reads at-rest with the post still in flight.+ # Defaulted False so pre-field payloads keep the finalize-goes-idle behavior.+ will_publish: bool = False@dataclass@@ -1197,7 +1201,13 @@ async def validate_chunk_activity(input: ValidateChunkInput) -> ValidateChunkResdef _build_and_finalize(- team_id: int, report_id: str, head_sha: str, run_index: int, issue_ids: list[str], urgency_threshold: str+ team_id: int,+ report_id: str,+ head_sha: str,+ run_index: int,+ issue_ids: list[str],+ urgency_threshold: str,+ will_publish: bool,) -> None:issues = load_run_issues(team_id=team_id, report_id=report_id, run_index=run_index, issue_ids=issue_ids)# Verdicts come from the DB (the same rows publish reads), so a partially-failed chunk shows the@@ -1222,6 +1232,7 @@ def _build_and_finalize(# The same snapshot the body above and the publish gate consume — stamped so the detail view# buckets this turn's findings by the gate that actually ran.urgency_threshold=urgency_threshold,+ will_publish=will_publish,)@@ -1231,7 +1242,13 @@ def _build_and_finalize(async def build_body_activity(input: BuildBodyInput) -> None:"""Render the review body and finalize the turn (store the body, bump the run watermark)."""await database_sync_to_async(_build_and_finalize, thread_sensitive=False)(- input.team_id, input.report_id, input.head_sha, input.run_index, input.issue_ids, input.urgency_threshold+ input.team_id,+ input.report_id,+ input.head_sha,+ input.run_index,+ input.issue_ids,+ input.urgency_threshold,+ input.will_publish,)@@ -1468,12 +1485,24 @@ async def finalize_status_comment_activity(input: FinalizeStatusCommentInput) ->)+def _fail_run(team_id: int, report_id: str) -> None:+ # The idle write comes first so a GitHub failure below can't skip it: on publishing runs+ # finalize defers going idle to the publish stage, so a run dying between finalize and publish+ # would otherwise sit ACTIVE (reading as in-progress in the UI) until the staleness cutoff.+ ReviewReport.objects.for_team(team_id).filter(id=report_id).update(status=ReviewReport.Status.IDLE)+ fail_status_comment(team_id, report_id)++@activity.defn@scoped_temporal()@close_db_connectionsasync def fail_status_comment_activity(input: StatusCommentInput) -> None:- """Rewrite the status comment as failed, so a dead run never reads as forever in progress."""- await database_sync_to_async(fail_status_comment, thread_sensitive=False)(input.team_id, input.report_id)+ """Return the dead run's report to rest and rewrite the status comment as failed.++ The idle write lives in this activity rather than as its own workflow command so in-flight+ histories replay unchanged (new unconditional commands break replay determinism).+ """+ await database_sync_to_async(_fail_run, thread_sensitive=False)(input.team_id, input.report_id)# --- The signals report's code_review receipt --------------------------------------------------------diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.pyindex 64fa71ec054e..5b62d51edcb9 100644--- a/products/review_hog/backend/temporal/workflow.py+++ b/products/review_hog/backend/temporal/workflow.py@@ -447,11 +447,14 @@ class ReviewPRWorkflow:return report_idacting_user_id = acting.acting_user_id+ # One gate, three consumers: the status comment, finalize's deferred idle write, and the+ # stage-7 publish dispatch all key off "this run publishes to a PR".+ publishes_to_pr = inputs.publish and meta.pr_number is not None# The PR's live status comment: posted once every gate has passed, refreshed by the pipeline# activities as they persist progress, and rewritten with the outcome below. Publish-path# only — eval / CLI / branch-target runs keep zero GitHub footprint. Best-effort throughout:# a status comment must never cost a review.- status_comment = inputs.publish and meta.pr_number is not None+ status_comment = publishes_to_prif status_comment:try:await workflow.execute_activity(@@ -557,13 +560,16 @@ class ReviewPRWorkflow:run_index=stage.run_index,issue_ids=dedup.issue_ids,urgency_threshold=acting.urgency_threshold,+ # Publishing runs stay ACTIVE through stage 7; publish/failure return them to rest.+ will_publish=publishes_to_pr,),start_to_close_timeout=_QUICK_TIMEOUT,retry_policy=_RETRY,)workflow.logger.info("STAGE 7/7 · Publish review")- if inputs.publish and meta.pr_number is not None:+ # The pr_number check is implied by the gate; restated so mypy narrows it to int.+ if publishes_to_pr and meta.pr_number is not None:publish_result = await workflow.execute_activity(publish_review_activity,PublishInput(@@ -586,8 +592,9 @@ class ReviewPRWorkflow:else:workflow.logger.info("Publishing disabled for this run (publish=False)")except Exception:- # A dead run must not read as forever in progress on the PR; best-effort so the status- # edit can never mask the original error.+ # A dead run must not read as forever in progress on the PR or in the Code review UI+ # (the activity also returns the report to rest, covering a publish that died with the+ # idle write still deferred); best-effort so the edit can never mask the original error.if status_comment:try:await workflow.execute_activity(diff --git a/products/review_hog/backend/tests/test_persistence.py b/products/review_hog/backend/tests/test_persistence.pyindex 96c1e4430222..ed7bd4688226 100644--- a/products/review_hog/backend/tests/test_persistence.py+++ b/products/review_hog/backend/tests/test_persistence.py@@ -109,6 +109,23 @@ class TestUpsertReviewReport(BaseTest):assert report.status == ReviewReport.Status.IDLEassert report.completed_head_sha == "sha-2" # what the finished turn reviewed, for read anchoring+ def test_finalize_defers_idle_for_publishing_runs(self) -> None:+ # On publishing runs the publish stage owns the idle write: going idle at finalize hands+ # the UI's poll a completed-but-unpublished row as the run's final state, freezing a wrong+ # "Not published" on screen until a manual refresh.+ report_id = upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())+ finalize_review_report(+ team_id=self.team.id,+ report_id=report_id,+ body_markdown="# report",+ run_index=1,+ head_sha="sha-1",+ will_publish=True,+ )+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)+ assert report.status == ReviewReport.Status.ACTIVE+ assert report.run_count == 1 # the turn still finalizes fully; only the idle write is deferred+def test_review_arm_is_drawn_once_and_sticky_across_turns(self) -> None:# Sticky-per-report is the arm draw's core invariant: a redraw on the update path would# flip a report's reviewer between turns, poisoning per-arm metrics and feeding one arm'sdiff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.pyindex 46f8b8669d4e..757e899ac32e 100644--- a/products/review_hog/backend/tests/test_publish_idempotency.py+++ b/products/review_hog/backend/tests/test_publish_idempotency.py@@ -139,6 +139,9 @@ class TestPublishIdempotency(BaseTest):# outcome classification reconstructs the published set from it, so a later settings change# can't rewrite what was posted.assert report.published_urgency_thresholds == {"1": "should_fix"}+ # Publishing runs arrive here still ACTIVE (finalize defers the idle write); the posted+ # save must restore rest or the row reads as in-progress until the staleness cutoff.+ assert report.status == ReviewReport.Status.IDLE@patch(_PUBLISH)@patch(_SNAPSHOT, return_value=None)@@ -147,6 +150,9 @@ class TestPublishIdempotency(BaseTest):report_id = self._report(published_head_sha="sha1")_publish(self.team.id, report_id, "sha1", 1, "PostHog", "posthog", 1, "should_fix")mock_publish.assert_not_called()+ # The skip exit must also restore rest: an activity retry can land here with the report+ # still deferred-ACTIVE from finalize.+ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).status == ReviewReport.Status.IDLE@patch(_PUBLISH)@patch(_SNAPSHOT, return_value=None)@@ -169,4 +175,7 @@ class TestPublishIdempotency(BaseTest):report_id = self._report()_publish(self.team.id, report_id, "sha1", 1, "PostHog", "posthog", 1, "should_fix")assert mock_publish.call_count == 1- assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).published_head_sha is None+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)+ assert report.published_head_sha is None+ # No watermark, but the turn is over: the no-post exit still restores rest.+ assert report.status == ReviewReport.Status.IDLEdiff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.pyindex 6c7716234b33..1ba37948e3d1 100644--- a/products/review_hog/backend/tests/test_reviews_api.py+++ b/products/review_hog/backend/tests/test_reviews_api.py@@ -493,6 +493,32 @@ class TestRecentReviewsAPI(APIBaseTest):"total": 2,}+ def test_publish_window_stays_in_progress_and_reads_finalizing(self) -> None:+ # On publishing runs finalize bumps run_count but defers the idle write to the publish+ # stage, so the report is briefly ACTIVE with no in-flight findings. The row must keep+ # reading in-progress ("finalizing", not a misread of the finished turn's working state as+ # "deduplicating"), so the UI's poll survives until the published flag is real.+ report = self._report(+ pr_number=3,+ acting_user=self.user,+ status=ReviewReport.Status.ACTIVE,+ head_sha="sha1",+ completed_head_sha="sha1",+ )++ row = self.client.get(self.url).json()["results"][0]+ assert row["pr_number"] == 3+ assert row["in_progress"] is True+ assert row["published"] is False+ assert row["progress"] == {"review_stage": "finalizing", "done": None, "total": None}++ # A resolution run holds the same ACTIVE-at-completed-head shape but with the head already+ # published — that window keeps its pre-existing label (relabeling it is a separate change).+ ReviewReport.objects.for_team(self.team.id).filter(id=report.id).update(published_head_sha="sha1")+ row = self.client.get(self.url).json()["results"][0]+ assert row["in_progress"] is True+ assert row["progress"]["review_stage"] != "finalizing"+def test_row_and_detail_anchor_to_the_completed_turn_during_a_re_review(self) -> None:# A re-review advances the live head_sha at turn START while run_count still points at the# previous turn — row stats and the detail's link-anchoring head must describe the COMPLETEDdiff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.pyindex 9a335c7c8f7a..149bb902abba 100644--- a/products/review_hog/backend/tests/test_status_comment.py+++ b/products/review_hog/backend/tests/test_status_comment.py@@ -22,6 +22,7 @@ from products.review_hog.backend.reviewer.status_comment import (render_in_progress_body,status_marker,)+from products.review_hog.backend.temporal.activities import _fail_run_MODULE = "products.review_hog.backend.reviewer.status_comment"_REQUEST = f"{_MODULE}.github_api_request"@@ -377,3 +378,16 @@ class TestFinalizeStatusComment(BaseTest):assert _patches(mock_request) == ["/repos/o/r/issues/comments/555"]body = mock_request.call_args.kwargs["json"]["body"]assert "couldn't finish this review" in body+++class TestFailRun(BaseTest):+ def test_returns_the_report_to_rest_even_without_a_status_comment(self) -> None:+ # Publishing runs defer finalize's idle write to the publish stage, so the failure path must+ # restore rest itself or a dead run reads as in-progress in the UI until the staleness+ # cutoff. A report with no status comment (nothing to edit on GitHub) must still go idle.+ report_id = upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())+ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).status == ReviewReport.Status.ACTIVE++ _fail_run(self.team.id, report_id)++ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).status == ReviewReport.Status.IDLEdiff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.pyindex d325665d6832..ee96414458dd 100644--- a/products/review_hog/backend/tests/test_temporal_workflow.py+++ b/products/review_hog/backend/tests/test_temporal_workflow.py@@ -115,6 +115,7 @@ async def _run_full_review_pr_workflow(review_calls: list[tuple[int, int, bool, str, tuple[str, ...]]] = []validate_calls: list[int] = []publish_calls: list[int] = []+ finalize_will_publish: list[bool] = []# Each code_review receipt appended to the signals report, as (outcome, review_url).receipt_calls: list[tuple[str, str | None]] = []# The outcome edit of the PR status comment, as (urgency_threshold, resolved_from, review_url) —@@ -234,6 +235,7 @@ async def _run_full_review_pr_workflow(@activity.defn(name="build_body_activity")async def build_body(input: BuildBodyInput) -> None:threshold_calls.append(("body", input.urgency_threshold))+ finalize_will_publish.append(input.will_publish)return None@activity.defn(name="publish_review_activity")@@ -347,6 +349,7 @@ async def _run_full_review_pr_workflow("review": review_calls,"validate": validate_calls,"publish": publish_calls,+ "finalize_will_publish": finalize_will_publish,"receipts": receipt_calls,"load_user_ids": load_user_ids,"thresholds": threshold_calls,@@ -374,6 +377,9 @@ async def test_review_pr_workflow_runs_all_stages_and_fans_out():assert {c[4] for c in wave} == {()} # the wave itself gets no cross-perspective contextassert sorted(recorded["validate"]) == [1, 2] # one session per chunk-with-issuesassert recorded["publish"] == [] # publish=False → never posts to GitHub+ # No publish stage means finalize keeps the idle write; deferring it here would strand the+ # report ACTIVE forever (nothing downstream ever restores rest on a no-publish run).+ assert recorded["finalize_will_publish"] == [False]# The RESOLVED acting user (3 from the resolve stub), not the None workflow input, threads into# the perspective, blind-spots, and validation loads — the per-user selection seam for each.assert recorded["load_user_ids"] == [3, 3, 3]@@ -426,6 +432,9 @@ async def test_review_pr_workflow_falls_back_to_dense_when_selection_fails():async def test_review_pr_workflow_publishes_only_when_publish_true():recorded = await _run_full_review_pr_workflow(publish=True)assert recorded["publish"] == [7] # publish=True → posts the review back to the PR+ # Publishing runs defer the idle write to the publish stage; dropping the flag re-opens the+ # window where a poll sees the run at rest with "Not published" still true and freezes on it.+ assert recorded["finalize_will_publish"] == [True]# The acting user's threshold snapshot (not the dataclass default) reaches both consumers, so# body counts and posted comments gate on the same set.assert recorded["thresholds"] == [("body", "must_fix"), ("publish", "must_fix")]diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.tsindex 39480a2438b2..285a5d2ae819 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts@@ -412,4 +412,96 @@ describe('reviewHogSettingsLogic', () => {// than offering a request the server rejects.expect(logic.values.moreReviewsAvailable).toBe(false)})++ it('keeps a slower baseline poll running when nothing is in progress', async () => {+ // Reviews started outside this page (the GitHub label, inbox auto-reviews, a teammate)+ // only ever appear via the baseline poll — reverting to dispose-on-idle makes the page+ // permanently stale until a manual refresh.+ jest.useFakeTimers()+ try {+ logic.mount()+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])++ await expectLogic(logic, () => {+ jest.advanceTimersByTime(30_000)+ }).toDispatchActions(['loadRecentReviews', 'loadRecentReviewsSuccess'])+ } finally {+ jest.useRealTimers()+ }+ })++ it('refreshes the stats and an open drawer when a watched run finishes', async () => {+ // A poll response is the only place a completion becomes visible: without the fan-out the+ // proof/effectiveness cards and an open drawer keep pre-completion numbers until reload.+ let finished = false+ useMocks({+ get: {+ '/api/projects/:team_id/review_hog/reviews/': () => [+ 200,+ {+ results: [{ id: 'r-live', in_progress: !finished, run_count: finished ? 1 : 0 }],+ has_more: false,+ },+ ],+ '/api/projects/:team_id/review_hog/reviews/r-live/': () => [200, reviewDetail('r-live', null)],+ },+ })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRecentReviewsSuccess']).toFinishAllListeners()++ logic.actions.openReviewDetailById('r-live')+ await expectLogic(logic).toDispatchActions(['loadReviewDetailSuccess'])++ finished = true+ await expectLogic(logic, () => logic.actions.loadRecentReviews()).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'loadPerspectiveStats',+ 'loadReviewDetail',+ ])+ })++ it('keeps the failure banner off for a background refresh blip', async () => {+ logic.mount()+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])+ useMocks({ get: { '/api/projects/:team_id/review_hog/reviews/': () => [500, {}] } })++ // The poll retries on its next tick and the prior rows stay on screen — flashing the+ // page-level banner over one blip would cry wolf every time a request hiccups.+ await expectLogic(logic, () => logic.actions.loadRecentReviews())+ .toDispatchActions(['loadRecentReviewsFailure'])+ .toNotHaveDispatchedActions(['markInitialLoadFailed'])+ expect(logic.values.initialLoadFailed).toBe(false)+ })++ it('flags a reviews failure with nothing loaded yet as an initial-load failure', async () => {+ // Without this the section sits on skeletons forever with no retry path offered.+ useMocks({ get: { '/api/projects/:team_id/review_hog/reviews/': () => [500, {}] } })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadRecentReviewsFailure', 'markInitialLoadFailed'])+ expect(logic.values.initialLoadFailed).toBe(true)+ })++ it('checks the list immediately when the tab becomes visible again', async () => {+ // The poll interval is paused while hidden and resumes with a full interval still to wait,+ // which reads as stale exactly when the user comes back to look.+ logic.mount()+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])++ await expectLogic(logic, () => {+ document.dispatchEvent(new Event('visibilitychange'))+ }).toDispatchActions(['loadRecentReviews'])+ })})diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.tsindex fae9dd6c49c5..a77ec36e291e 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts@@ -54,6 +54,18 @@ export const REVIEW_PRIORITY_RANK: Record<ReviewIssuePriorityEnumApi, number> =// While a review is running, the list refreshes on this cadence so the stage/progress row is live.const IN_PROGRESS_POLL_INTERVAL_MS = 10_000+// With nothing running the list still refreshes, just slower: reviews started outside this page+// (the GitHub label, inbox auto-reviews, a teammate) have no other way to appear, and a finished+// run's published state can land moments after its last in-progress response. Hidden tabs pause+// the poll entirely, so the idle cadence only spends requests someone could actually see.+const IDLE_POLL_INTERVAL_MS = 30_000++/** What the poll remembers about a row between responses, to spot a run finishing. */+interface ReviewRunMarker {+ inProgress: boolean+ runCount: number+}+// How long after triggering a review the list keeps polling for its report row to appear — the row// is created seconds after the 202 by the workflow's fetch step, but a run that dies before creating// it must not keep the list polling forever.@@ -318,6 +330,9 @@ export interface reviewHogSettingsLogicActions {validators: ReviewValidatorConfigApi[]payload?: any}+ markInitialLoadFailed: () => {+ value: true+ }openPipelineDetail: () => {value: true}@@ -486,10 +501,13 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([submitTriggerReview: (runMode: RunModeEnumApi = RunModeEnumApi.Review) => ({ runMode }),submitTriggerReviewStarted: true,submitTriggerReviewFinished: true,- // Keeps the recent-reviews poll alive until a just-triggered review's report row appears —- // without it the poll only arms when some other review is already visibly running.+ // Keeps the recent-reviews poll on the tight cadence until a just-triggered review's report+ // row appears; without it the poll only tightens when some review is already visibly running.startTriggeredReviewWatch: true,stopTriggeredReviewWatch: true,+ // Flags a load failure as the page-level one. Dispatched by the failure listeners only when+ // the failing surface has nothing loaded yet, so a background poll blip stays silent.+ markInitialLoadFailed: true,}),loaders(({ values }) => ({@@ -745,10 +763,11 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([loadBlindSpotsFailure: () => true,loadValidatorsFailure: () => true,loadResolutionSkillsFailure: () => true,- // recentReviews/perspectiveStats stay null on failure and their sections render- // skeletons while null — without these the skeletons are permanent, with no retry.- loadRecentReviewsFailure: () => true,- loadPerspectiveStatsFailure: () => true,+ // recentReviews/perspectiveStats failures arrive via markInitialLoadFailed instead:+ // their loaders also run on background polls, where a one-off failure just retries+ // on the next tick, and only a failure with nothing loaded yet (sections stuck on+ // skeletons, no retry path) is a page-level one.+ markInitialLoadFailed: () => true,},],creatingSkillKind: [@@ -840,25 +859,48 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([}),listeners(({ actions, values, cache }) => ({- // Poll while any review is running so the stage row moves — or while a just-triggered- // review's row hasn't appeared yet; the disposable auto-pauses on hidden tabs and is torn- // down on unmount.+ // The poll never stops while the page is mounted (hidden tabs pause it); it only changes+ // cadence: tight while a review is running or freshly triggered so the stage row moves,+ // relaxed otherwise so externally-started reviews still appear. Re-adding under the same+ // key replaces the previous timer, so every response re-arms the poll at the right speed.loadRecentReviewsSuccess: () => {const anyInProgress = values.recentReviews?.some((review) => review.in_progress) ?? false// The watch deliberately runs its full bounded window instead of stopping when an// in-progress row shows up: an unrelated already-running review would satisfy that check- // and could finish before the triggered row appears, killing the poll too early. The- // cost is at most the watch window of idle 10s polls after a fast run completes.- if (anyInProgress || values.awaitingTriggeredReview) {- cache.disposables.add(() => {- const pollTimer = window.setInterval(- () => actions.loadRecentReviews(),- IN_PROGRESS_POLL_INTERVAL_MS- )- return () => clearInterval(pollTimer)- }, 'inProgressPoll')- } else {- cache.disposables.dispose('inProgressPoll')+ // and could finish before the triggered row appears, relaxing the cadence too early. The+ // cost is at most the watch window of tight 10s polls after a fast run completes.+ const pollInterval =+ anyInProgress || values.awaitingTriggeredReview ? IN_PROGRESS_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS+ cache.disposables.add(() => {+ const pollTimer = window.setInterval(() => actions.loadRecentReviews(), pollInterval)+ return () => clearInterval(pollTimer)+ }, 'reviewsPoll')+ // A run finishing moves numbers beyond the list: the stats cards aggregate completed+ // turns, and an open drawer still shows the report's previous turn. A poll response is+ // the only place a completion becomes visible, so fan the refresh out from here.+ const previousRuns: Map<string, ReviewRunMarker> | undefined = cache.lastSeenRuns+ const currentRuns = new Map<string, ReviewRunMarker>()+ for (const review of values.recentReviews ?? []) {+ currentRuns.set(review.id, { inProgress: review.in_progress, runCount: review.run_count })+ }+ cache.lastSeenRuns = currentRuns+ if (previousRuns) {+ const finishedIds = Array.from(currentRuns.entries())+ .filter(([id, run]) => {+ const before = previousRuns.get(id)+ return !!before && ((before.inProgress && !run.inProgress) || run.runCount > before.runCount)+ })+ .map(([id]) => id)+ if (finishedIds.length) {+ actions.loadPerspectiveStats()+ if (+ values.reviewDrawerOpen &&+ values.openedReviewId &&+ finishedIds.includes(values.openedReviewId)+ ) {+ actions.loadReviewDetail(values.openedReviewId)+ }+ }}// No reviews of the user's own PRs: default to the whole project so the block isn't// empty — only until the user picks a scope themselves.@@ -885,10 +927,13 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([cache.disposables.dispose('triggeredReviewWatch')},setReviewsScope: () => {+ // A different scope is a different list; start the finished-run comparison fresh.+ cache.lastSeenRuns = undefinedactions.loadRecentReviews()actions.loadPerspectiveStats()},applyDefaultReviewsScope: () => {+ cache.lastSeenRuns = undefinedactions.loadRecentReviews()actions.loadPerspectiveStats()},@@ -907,6 +952,19 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([// The global loaders toast already surfaced the error; just reconcile the optimistic state.actions.loadSettings()},+ // A background refresh failing is not a page-level failure: the poll retries on its next+ // tick and the prior rows stay on screen. Only a failure with nothing loaded yet (the+ // sections would sit on skeletons with no retry path) raises the error banner.+ loadRecentReviewsFailure: () => {+ if (values.recentReviewsPage === null) {+ actions.markInitialLoadFailed()+ }+ },+ loadPerspectiveStatsFailure: () => {+ if (values.perspectiveStats === null) {+ actions.markInitialLoadFailed()+ }+ },togglePerspective: async ({ skillName, enabled }) => {// Min-1 floor, mirrored from the backend so the block is instant (the server still 400s).const enabledCount = values.perspectives?.filter((p) => p.enabled).length ?? 0@@ -1109,7 +1167,25 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([},})),- afterMount(({ actions }) => {+ afterMount(({ actions, cache }) => {actions.loadAll()+ // One immediate list check on tab return. The poll's own interval is paused while hidden+ // and resumes with a full interval still to wait, which reads as stale exactly when the+ // user looks. Registered non-pausing: a paused listener is re-attached during the same+ // visibilitychange dispatch it needs to observe, and listeners added mid-dispatch don't+ // run for that event.+ cache.disposables.add(+ () => {+ const onVisibilityChange = (): void => {+ if (!document.hidden) {+ actions.loadRecentReviews()+ }+ }+ document.addEventListener('visibilitychange', onVisibilityChange)+ return () => document.removeEventListener('visibilitychange', onVisibilityChange)+ },+ 'visibilityRefresh',+ { pauseOnPageHidden: false }+ )}),])