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): record failed and skipped runs as outcome notes (#114908)

Julian Bez3afffb6673b7
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index c9cab7983ce2..34755514b3eb 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -3,7 +3,7 @@ import logging
from typing import Any, cast, get_args
from django.db import models
-from django.db.models import Max, Q, QuerySet
+from django.db.models import Q, QuerySet
from django.utils import timezone
from drf_spectacular.openapi import AutoSchema
@@ -22,7 +22,7 @@ from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
-from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
+from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.preferences import UrgencyThreshold
from products.review_hog.backend.requested_reviews import (
RUN_MODE_FLASH,
@@ -44,7 +44,6 @@ from products.review_hog.backend.reviewer.models.issues_review import IssuePrior
from products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksList
from products.review_hog.backend.reviewer.persistence import TurnFindingsBundle, load_chunk_set, load_findings_bundle
from products.review_hog.backend.reviewer.progress import (
- IN_PROGRESS_STALE_AFTER,
RESOLUTION_COMPLETED,
RESOLUTION_RESOLVING,
RESOLUTION_STOPPED,
@@ -54,6 +53,7 @@ from products.review_hog.backend.reviewer.progress import (
SnapshotStats,
TurnMarker,
TurnStats,
+ in_progress_report_ids,
latest_resolution_summaries,
progress_payload,
resolution_states,
@@ -517,39 +517,6 @@ class _PageEnvelopeSchema(AutoSchema):
return operation_id
-def _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 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 showing
- a stuck spinner forever.
-
- `finding_outcome` is excluded because it is the one artefact type not written by a turn: the
- outcome sweep appends it after the PR merges, which can be long after the run ended. Counting it
- would restart the staleness window and re-show the spinner for a report with nothing running —
- exactly the crashed-and-never-finalized report (status only leaves ACTIVE on a successful
- finalize) that the ageing-out exists to retire.
- """
- candidates = [report for report in reports if report.status == ReviewReport.Status.ACTIVE]
- if not candidates:
- return set()
- latest_artefact = dict(
- ReviewReportArtefact.objects.for_team(team_id)
- .filter(report_id__in=[report.id for report in candidates])
- .exclude(type=ReviewReportArtefact.ArtefactType.FINDING_OUTCOME)
- .values_list("report_id")
- .annotate(latest=Max("created_at"))
- .values_list("report_id", "latest")
- )
- cutoff = timezone.now() - IN_PROGRESS_STALE_AFTER
- fresh: set[str] = set()
- for report in candidates:
- last_activity = max(filter(None, [report.updated_at, latest_artefact.get(report.id)]), default=None)
- if last_activity is not None and last_activity >= cutoff:
- fresh.add(str(report.id))
- return fresh
-
-
def _turn_progress(
team_id: int,
reports: list[ReviewReport],
@@ -797,7 +764,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
:probe_limit
]
)
- in_progress_ids = _in_progress_report_ids(team_id, running_first_turn + running_re_review + completed)
+ in_progress_ids = in_progress_report_ids(team_id, running_first_turn + running_re_review + completed)
# Visibly running first (first turns, then re-reviews), then recent completed — deduped so a
# re-review that also ranks in the completed slice keeps its front position.
seen: set[str] = set()
@@ -1043,7 +1010,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
pairs = bundle.turn(report_id, run_index)
chunk_set = load_chunk_set(team_id=team_id, report_id=report_id, head_sha=turn_head) if turn_head else None
resolutions = resolution_states(team_id, [report])
- in_progress_ids = _in_progress_report_ids(team_id, [report])
+ in_progress_ids = in_progress_report_ids(team_id, [report])
progress = _turn_progress(team_id, [report], in_progress_ids, resolutions, bundle).get(report_id)
def sort_key(payload: dict[str, Any]) -> tuple[int, str]:
diff --git a/products/review_hog/backend/reviewer/artefact_content.py b/products/review_hog/backend/reviewer/artefact_content.py
index 1bf96c983fce..f79a2114aa8f 100644
--- a/products/review_hog/backend/reviewer/artefact_content.py
+++ b/products/review_hog/backend/reviewer/artefact_content.py
@@ -349,6 +349,28 @@ class TurnMarkerArtefact(BaseModel):
)
+RUN_OUTCOME_NOTE_AUTHOR = "review_hog_run_outcome"
+
+
+class RunOutcomeNote(NoteArtefact):
+ """Content for a `note` artefact that records a review turn or resolution run that ended without a result.
+
+ A completed turn leaves a `turn_marker` and a stamped report, and a resolution run leaves its
+ closing note. A failed turn, a dropped Standard request, and a skipped resolution run leave
+ nothing else, so a status reader cannot tell them from a request that is still waiting. It stays
+ a `note` so that no new artefact type (and no migration) is needed: readers that parse it as a
+ plain `NoteArtefact` ignore the extra fields.
+ """
+
+ author: str | None = Field(default=RUN_OUTCOME_NOTE_AUTHOR, description="Always `review_hog_run_outcome`.")
+ stage: Literal["review", "resolution"] = Field(description="Which run ended: a review turn or a resolution run.")
+ outcome: Literal["skipped", "failed"] = Field(description="How the run ended.")
+ reason: str = Field(description="Short reason code, e.g. flash_after_full, review_failed, pr_not_open.")
+ run_index: int | None = Field(default=None, description="The review turn (1-based) for a review run.")
+ review_mode: str | None = Field(default=None, description="The review mode (full or flash) for a review run.")
+ head_sha: str | None = Field(default=None, description="The PR head the run targeted, when known.")
+
+
# Reused leaf models back the work-log entry types; ReviewHog adds findings + verdicts. The
# working-state types (chunk_set / perspective_result) are per-turn pipeline scaffolding the
# DB-driven resume reads back — head_sha-scoped, latest-wins within a turn.
@@ -386,7 +408,11 @@ ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {
"pr_snapshot": PRSnapshotArtefact,
"turn_marker": TurnMarkerArtefact,
}
-_ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model in ARTEFACT_CONTENT_SCHEMAS.items()}
+_ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {
+ **{model: t for t, model in ARTEFACT_CONTENT_SCHEMAS.items()},
+ # A note subtype: it persists as `note`, and `note` rows still parse as the plain NoteArtefact.
+ RunOutcomeNote: "note",
+}
def artefact_type_for(content: BaseModel) -> str:
diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.py
index 39029629d086..19e88ed27da7 100644
--- a/products/review_hog/backend/reviewer/progress.py
+++ b/products/review_hog/backend/reviewer/progress.py
@@ -12,9 +12,9 @@ import operator
from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import reduce
-from typing import Any
+from typing import Any, Final, Literal
-from django.db.models import Func, IntegerField, JSONField, Max, Q, QuerySet
+from django.db.models import Case, CharField, Func, IntegerField, JSONField, Max, Q, QuerySet, Value, When
from django.db.models.fields.json import KeyTextTransform, KeyTransform
from django.db.models.functions import Cast
from django.utils import timezone
@@ -25,9 +25,11 @@ from posthog.dataclasses import frozen
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact, ReviewSkillConfig
from products.review_hog.backend.reviewer.artefact_content import (
+ RUN_OUTCOME_NOTE_AUTHOR,
PerspectiveSelectionArtefact,
ResolutionRunArtefact,
ReviewIssueFinding,
+ RunOutcomeNote,
ValidationVerdict,
)
from products.review_hog.backend.reviewer.constants import BLIND_SPOT_PASS_NUMBER
@@ -38,6 +40,7 @@ from products.review_hog.backend.reviewer.skill_loader import (
CANONICAL_PERSPECTIVE_SKILL_NAMES,
REVIEW_HOG_PERSPECTIVE_PREFIX,
)
+from products.signals.backend.artefact_attribution import ArtefactAttribution
logger = logging.getLogger(__name__)
@@ -286,6 +289,92 @@ def turn_markers(team_id: int, report_ids: list[str]) -> dict[tuple[str, int], T
return markers
+RUN_STAGE_REVIEW: Final = "review"
+RUN_STAGE_RESOLUTION: Final = "resolution"
+RUN_OUTCOME_SKIPPED: Final = "skipped"
+RUN_OUTCOME_FAILED: Final = "failed"
+REVIEW_FAILED_REASON = "review_failed"
+
+
+@frozen
+class RunOutcomeMarker:
+ """A review turn or resolution run that ended without a result, from its run outcome `note`."""
+
+ stage: str # RUN_STAGE_REVIEW | RUN_STAGE_RESOLUTION
+ outcome: str # RUN_OUTCOME_SKIPPED | RUN_OUTCOME_FAILED
+ reason: str
+ run_index: int | None
+ review_mode: str | None
+ head_sha: str | None
+ created_at: datetime
+
+
+def record_run_outcome(
+ team_id: int,
+ report_id: str,
+ *,
+ stage: Literal["review", "resolution"],
+ outcome: Literal["skipped", "failed"],
+ reason: str,
+ run_index: int | None = None,
+ review_mode: str | None = None,
+ head_sha: str | None = None,
+) -> None:
+ """Append a run outcome `note`. Best-effort, because a status record must never fail the run it describes."""
+ run_label = f"Review turn {run_index}" if stage == RUN_STAGE_REVIEW and run_index else f"The {stage} run"
+ try:
+ ReviewReportArtefact.add_log(
+ team_id=team_id,
+ report_id=report_id,
+ content=RunOutcomeNote(
+ note=f"{run_label} {outcome} ({reason}).",
+ stage=stage,
+ outcome=outcome,
+ reason=reason,
+ run_index=run_index,
+ review_mode=review_mode,
+ head_sha=head_sha,
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+ except Exception:
+ logger.exception("Could not record the %s %s outcome for report %s", stage, outcome, report_id)
+
+
+def run_outcome_markers(
+ team_id: int, report_ids: list[str], since: datetime | None = None
+) -> dict[str, list[RunOutcomeMarker]]:
+ """Each report's run outcome notes written at or after `since`, oldest first."""
+ rows = (
+ ReviewReportArtefact.objects.for_team(team_id)
+ .filter(report_id__in=report_ids, type=ReviewReportArtefact.ArtefactType.NOTE)
+ .annotate(note_author=KeyTextTransform("author", _content_json()))
+ .filter(note_author=RUN_OUTCOME_NOTE_AUTHOR)
+ )
+ if since is not None:
+ rows = rows.filter(created_at__gte=since)
+ markers: dict[str, list[RunOutcomeMarker]] = {report_id: [] for report_id in report_ids}
+ for row in rows.order_by("created_at", "id").values("report_id", "content", "created_at"):
+ report_id = str(row["report_id"])
+ try:
+ note = RunOutcomeNote.model_validate_json(row["content"])
+ except ValidationError as e:
+ logger.warning("Skipping unparseable run outcome note for report %s: %s", report_id, e)
+ continue
+ markers.setdefault(report_id, []).append(
+ RunOutcomeMarker(
+ stage=note.stage,
+ outcome=note.outcome,
+ reason=note.reason,
+ run_index=note.run_index,
+ review_mode=note.review_mode,
+ head_sha=note.head_sha,
+ created_at=row["created_at"],
+ )
+ )
+ return markers
+
+
@frozen
class ResolutionRunState:
"""The report's latest resolution run, as the list row and the drawer render it."""
@@ -327,6 +416,30 @@ class _RunSignals:
activity_latest: dict[str, datetime]
+def _activity_artefacts(queryset: QuerySet) -> QuerySet:
+ """Artefacts that show a run is moving, for the staleness window.
+
+ `finding_outcome` rows come from the outcome sweep after the PR merges, and run outcome notes
+ record that a run already ended. Neither one is a running turn, so counting them would show a
+ dead run as live for another staleness window.
+ """
+ note_author = Case(
+ When(
+ type=ReviewReportArtefact.ArtefactType.NOTE,
+ then=KeyTextTransform("author", _content_json()),
+ ),
+ default=Value(None),
+ output_field=CharField(),
+ )
+ # The author is NULL on every non-note row. A plain `.exclude()` on an annotation compiles to
+ # `NOT (author = x)`, which is NULL for those rows and drops them, so keep NULL authors explicitly.
+ return (
+ queryset.exclude(type=ReviewReportArtefact.ArtefactType.FINDING_OUTCOME)
+ .annotate(activity_note_author=note_author)
+ .filter(Q(activity_note_author__isnull=True) | ~Q(activity_note_author=RUN_OUTCOME_NOTE_AUTHOR))
+ )
+
+
def _latest_created_at(queryset: QuerySet) -> dict[str, datetime]:
rows = queryset.values_list("report_id").annotate(latest=Max("created_at")).values_list("report_id", "latest")
return {str(report_id): latest for report_id, latest in rows}
@@ -368,7 +481,7 @@ def _run_signals(team_id: int, report_ids: list[str]) -> _RunSignals:
.annotate(note_author=KeyTextTransform("author", _content_json()))
.filter(note_author=RESOLUTION_RUN_NOTE_AUTHOR)
),
- activity_latest=_latest_created_at(scoped.exclude(type=ReviewReportArtefact.ArtefactType.FINDING_OUTCOME)),
+ activity_latest=_latest_created_at(_activity_artefacts(scoped)),
)
@@ -394,7 +507,7 @@ def _live_resolution_runs(
A run drops out when a newer review turn superseded it (a `pr_snapshot` after the run anchor) or
it completed (a closing run `note` after the anchor). Activity liveness reuses the same signal
- `_in_progress_report_ids` uses for review turns, so the two can't disagree about "visibly moving".
+ `in_progress_report_ids` uses for review turns, so the two can't disagree about "visibly moving".
"""
signals = _run_signals(team_id, list(runs))
live: dict[str, tuple[ResolutionRunArtefact, datetime]] = {}
@@ -530,6 +643,39 @@ def latest_resolution_summaries(team_id: int, reports: list[ReviewReport]) -> di
return summaries
+def 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 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 showing
+ a stuck spinner forever.
+
+ `finding_outcome` is excluded because it is the one artefact type not written by a turn: the
+ outcome sweep appends it after the PR merges, which can be long after the run ended. Counting it
+ would restart the staleness window and re-show the spinner for a report with nothing running —
+ exactly the crashed-and-never-finalized report (status only leaves ACTIVE on a successful
+ finalize) that the ageing-out exists to retire.
+ """
+ candidates = [report for report in reports if report.status == ReviewReport.Status.ACTIVE]
+ if not candidates:
+ return set()
+ latest_artefact = dict(
+ _activity_artefacts(
+ ReviewReportArtefact.objects.for_team(team_id).filter(report_id__in=[report.id for report in candidates])
+ )
+ .values_list("report_id")
+ .annotate(latest=Max("created_at"))
+ .values_list("report_id", "latest")
+ )
+ cutoff = timezone.now() - IN_PROGRESS_STALE_AFTER
+ fresh: set[str] = set()
+ for report in candidates:
+ last_activity = max(filter(None, [report.updated_at, latest_artefact.get(report.id)]), default=None)
+ if last_activity is not None and last_activity >= cutoff:
+ fresh.add(str(report.id))
+ return fresh
+
+
def _expected_reads(team_id: int, report: ReviewReport, turn: TurnStats) -> int | None:
"""How many (pass, chunk) reviews this turn should produce.
@@ -554,7 +700,7 @@ def _expected_reads(team_id: int, report: ReviewReport, turn: TurnStats) -> int
return chunk_count * (perspectives + 1)
-def _in_publish_window(report: ReviewReport) -> bool:
+def in_publish_window(report: ReviewReport) -> bool:
"""Whether the turn finished but has not published yet.
On publishing runs finalize defers the idle write to the publish stage, so the report is still
@@ -600,7 +746,7 @@ def progress_payload(
A single-agent turn gets its own stages once its fetch has recorded the design.
"""
if snapshot.head_matched and snapshot.review_design == REVIEW_DESIGN_SINGLE_AGENT:
- return _single_agent_progress(turn, current_pairs, _in_publish_window(report))
+ return _single_agent_progress(turn, current_pairs, in_publish_window(report))
if current_pairs:
judged = sum(1 for _, verdict in current_pairs if verdict is not None)
if judged >= len(current_pairs):
@@ -610,7 +756,7 @@ def progress_payload(
# "deduplicating". Relabeling a resolution run's ACTIVE 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 _in_publish_window(report):
+ if in_publish_window(report):
return {"review_stage": "finalizing", "done": None, "total": None}
if turn.chunk_count is not None:
done = turn.perspective_reads or 0
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 879264239999..cf6e3ef8577a 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -37,7 +37,7 @@ from products.review_hog.backend.automatic_reviews import automatic_flash_allowe
from products.review_hog.backend.models import ReviewProjectSettings, ReviewReport, ReviewUserSettings
from products.review_hog.backend.pr_owner import PullRequestOwnerResolver
from products.review_hog.backend.preferences import ReviewPreferences
-from products.review_hog.backend.review_request_rules import ResolutionGate, full_review_published
+from products.review_hog.backend.review_request_rules import ResolutionGate, ReviewRequestRefusal, full_review_published
from products.review_hog.backend.reviewer.constants import (
ALREADY_RAISED_SHOWN,
CHUNKING_MODEL,
@@ -100,6 +100,14 @@ from products.review_hog.backend.reviewer.persistence import (
replace_dropped_findings,
upsert_review_report,
)
+from products.review_hog.backend.reviewer.progress import (
+ REVIEW_FAILED_REASON,
+ RUN_OUTCOME_FAILED,
+ RUN_OUTCOME_SKIPPED,
+ RUN_STAGE_REVIEW,
+ in_publish_window,
+ record_run_outcome,
+)
from products.review_hog.backend.reviewer.push_gate import SYSTEM_ONE_SKIP_BELOW, PushGate, PushGateDecision
from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT
from products.review_hog.backend.reviewer.review_state import review_already_published
@@ -863,6 +871,23 @@ def _flash_after_full(input: ResolveActingUserInput) -> bool:
return full_review_published(ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).first())
+def _record_flash_after_full(team_id: int, report_id: str) -> None:
+ """Record the dropped Standard request, so a status reader sees it ended instead of waiting forever."""
+ report = ReviewReport.objects.for_team(team_id).filter(id=report_id).only("run_count", "head_sha").first()
+ if report is None:
+ return
+ record_run_outcome(
+ team_id,
+ report_id,
+ stage=RUN_STAGE_REVIEW,
+ outcome=RUN_OUTCOME_SKIPPED,
+ reason=ReviewRequestRefusal.FLASH_AFTER_FULL.value,
+ run_index=report.run_count + 1,
+ review_mode=REVIEW_MODE_FLASH,
+ head_sha=report.head_sha,
+ )
+
+
def _resolve_acting_user(input: ResolveActingUserInput) -> ResolveActingUserResult:
# Resolved even on override runs: the owner decides resolution and the clean-review media,
# whoever asked for the review.
@@ -882,11 +907,14 @@ def _resolve_acting_user(input: ResolveActingUserInput) -> ResolveActingUserResu
if acting_user_id is None and input.trigger_source == TRIGGER_LABEL:
acting_user_id, resolved_from = input.default_user_id, "default"
automatic_allowed = input.trigger_source == TRIGGER_AUTOMATIC and _automatic_review_allowed(input, acting_user_id)
- if (input.trigger_source == TRIGGER_AUTOMATIC and not automatic_allowed) or _flash_after_full(input):
+ flash_after_full = _flash_after_full(input)
+ if (input.trigger_source == TRIGGER_AUTOMATIC and not automatic_allowed) or flash_after_full:
if input.report_id is not None:
ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(
status=ReviewReport.Status.IDLE
)
+ if flash_after_full and input.report_id is not None:
+ _record_flash_after_full(input.team_id, input.report_id)
return ResolveActingUserResult(acting_user_id=None)
if acting_user_id is None:
return ResolveActingUserResult(acting_user_id=None)
@@ -2217,6 +2245,19 @@ def _fail_run(team_id: int, report_id: str, review_mode: str = REVIEW_MODE_FULL)
# 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)
+ report = ReviewReport.objects.for_team(team_id).filter(id=report_id).first()
+ if report is not None:
+ record_run_outcome(
+ team_id,
+ report_id,
+ stage=RUN_STAGE_REVIEW,
+ outcome=RUN_OUTCOME_FAILED,
+ reason=REVIEW_FAILED_REASON,
+ # A run that dies in the publish window already counts its turn in `run_count`.
+ run_index=report.run_count if in_publish_window(report) else report.run_count + 1,
+ review_mode=review_mode,
+ head_sha=report.head_sha,
+ )
fail_status_comment(team_id, report_id, review_mode=review_mode)
diff --git a/products/review_hog/backend/temporal/resolution.py b/products/review_hog/backend/temporal/resolution.py
index 5f6cbc483c0a..c4329ecb4f4f 100644
--- a/products/review_hog/backend/temporal/resolution.py
+++ b/products/review_hog/backend/temporal/resolution.py
@@ -58,7 +58,13 @@ from products.review_hog.backend.reviewer.persistence import (
persist_thread_verdict,
upsert_review_report,
)
-from products.review_hog.backend.reviewer.progress import RESOLUTION_RUN_NOTE_AUTHOR, resolution_states
+from products.review_hog.backend.reviewer.progress import (
+ RESOLUTION_RUN_NOTE_AUTHOR,
+ RUN_OUTCOME_SKIPPED,
+ RUN_STAGE_RESOLUTION,
+ record_run_outcome,
+ resolution_states,
+)
from products.review_hog.backend.reviewer.sandbox.executor import (
MultiTurnSession,
continue_sandbox_session,
@@ -281,6 +287,31 @@ def _commit_hold_for_run(input: ResolveThreadsInput, prepared: "_PreparedRun") -
)
+def _record_resolution_skip(
+ input: ResolveThreadsInput, reason: str, *, head_sha: str | None, report_id: str | None = None
+) -> None:
+ """Record why the run did nothing, so a status reader sees it ended instead of waiting forever."""
+ if report_id is None:
+ report = (
+ ReviewReport.objects.for_team(input.team_id)
+ .filter(repository__iexact=f"{input.owner}/{input.repo}", pr_number=input.pr_number)
+ .only("id")
+ .first()
+ )
+ # The gates run before the report upsert, so a PR that has no report yet has nowhere to record the skip.
+ if report is None:
+ return
+ report_id = str(report.id)
+ record_run_outcome(
+ input.team_id,
+ report_id,
+ stage=RUN_STAGE_RESOLUTION,
+ outcome=RUN_OUTCOME_SKIPPED,
+ reason=reason,
+ head_sha=head_sha,
+ )
+
+
def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResult:
"""Fetch + gate + pre-filter; returns the prepared work-list, or the run result for a clean no-op."""
# The run's one installation-selection probe — it doubles as the access gate. Deliveries reuse
@@ -297,6 +328,7 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResu
non_retryable=True,
)
if pr_metadata.state != "open":
+ _record_resolution_skip(input, "pr_not_open", head_sha=pr_metadata.head_sha)
return ResolutionRunResult(skipped_reason="pr_not_open")
# Every trigger reaches this gate, so no path writes to a branch whose owner did not opt in. The
# fork check above makes the head branch the base repository's, which the Inbox link needs.
@@ -313,6 +345,9 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResu
input.repo,
input.pr_number,
)
+ _record_resolution_skip(
+ input, ReviewRequestRefusal.RESOLUTION_NOT_OPTED_IN.value, head_sha=pr_metadata.head_sha
+ )
return ResolutionRunResult(skipped_reason=ReviewRequestRefusal.RESOLUTION_NOT_OPTED_IN.value)
pr_url = input.pr_url or f"https://github.com/{input.owner}/{input.repo}/pull/{input.pr_number}"
@@ -359,10 +394,10 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResu
)
triage, overflow = [], 0
if not triage and not redeliver:
- result = ResolutionRunResult(
- report_id=report_id, skipped_reason=hold.value if hold else "no_unresolved_threads", skipped=skipped
- )
+ skipped_reason = hold.value if hold else "no_unresolved_threads"
+ result = ResolutionRunResult(report_id=report_id, skipped_reason=skipped_reason, skipped=skipped)
_append_run_note(input, report_id, result)
+ _record_resolution_skip(input, skipped_reason, head_sha=pr_metadata.head_sha, report_id=report_id)
_idle_report(input.team_id, report_id)
return result
diff --git a/products/review_hog/backend/tests/test_acting_user.py b/products/review_hog/backend/tests/test_acting_user.py
index cf0a2dbf5f32..9a8d4c48c889 100644
--- a/products/review_hog/backend/tests/test_acting_user.py
+++ b/products/review_hog/backend/tests/test_acting_user.py
@@ -12,6 +12,7 @@ from products.review_hog.backend.models import (
ReviewRepository,
ReviewUserSettings,
)
+from products.review_hog.backend.reviewer.progress import run_outcome_markers
from products.review_hog.backend.temporal.activities import ResolveActingUserInput, _resolve_acting_user
from products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC, TRIGGER_LABEL, TRIGGER_MANUAL
@@ -174,6 +175,9 @@ class TestResolveActingUser(BaseTest):
assert result.acting_user_id == (self.user.id if runs else None)
report.refresh_from_db()
assert report.status == (ReviewReport.Status.ACTIVE if runs else ReviewReport.Status.IDLE)
+ markers = run_outcome_markers(self.team.id, [str(report.id)])[str(report.id)]
+ expected = [] if runs else [("skipped", "flash_after_full", 1, "flash")]
+ assert [(m.outcome, m.reason, m.run_index, m.review_mode) for m in markers] == expected
def test_settings_row_flows_into_the_result(self) -> None:
# The user's saved preferences must reach the workflow — if resolve stops loading any of them,
diff --git a/products/review_hog/backend/tests/test_resolution_activity.py b/products/review_hog/backend/tests/test_resolution_activity.py
index 6ee9a6c73dfe..1ed72ea2a6d9 100644
--- a/products/review_hog/backend/tests/test_resolution_activity.py
+++ b/products/review_hog/backend/tests/test_resolution_activity.py
@@ -24,6 +24,7 @@ from products.review_hog.backend.reviewer.lazy_seed import sync_canonical_resolu
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.models.thread_resolution import CommitHold, ThreadResolution
from products.review_hog.backend.reviewer.persistence import load_thread_verdicts, persist_thread_verdict
+from products.review_hog.backend.reviewer.progress import RESOLUTION_RUN_NOTE_AUTHOR, run_outcome_markers
from products.review_hog.backend.reviewer.tools.github_threads import FixCommitInspection, ReviewThread, ThreadComment
from products.review_hog.backend.temporal.resolution import (
FailResolutionInput,
@@ -538,8 +539,12 @@ class TestResolutionPersistenceAndDelivery(BaseTest):
assert result.skipped_reason == "no_unresolved_threads"
report = ReviewReport.objects.for_team(self.team.id).get(repository="posthog/posthog", pr_number=123)
assert report.status == ReviewReport.Status.IDLE
- note = ReviewReportArtefact.objects.for_team(self.team.id).get(report_id=report.id, type="note")
+ note = ReviewReportArtefact.objects.for_team(self.team.id).get(
+ report_id=report.id, type="note", content__contains=RESOLUTION_RUN_NOTE_AUTHOR
+ )
assert "0 thread(s) triaged" in note.content
+ markers = run_outcome_markers(self.team.id, [str(report.id)])[str(report.id)]
+ assert [(m.stage, m.outcome, m.reason) for m in markers] == [("resolution", "skipped", "no_unresolved_threads")]
# No queued threads means no progress anchor — a total=0 run artefact would render this
# clean no-op as a crashed run once it aged past the staleness window.
assert (
@@ -872,3 +877,42 @@ class TestResolutionOwnerGate(BaseTest):
else:
assert isinstance(result, ResolutionRunResult)
assert result.skipped_reason == "resolution_not_opted_in"
+
+ @parameterized.expand(
+ [
+ ("closed_pr", "closed", True, "pr_not_open"),
+ ("owner_did_not_opt_in", "open", True, "resolution_not_opted_in"),
+ ("no_report_yet", "open", False, None),
+ ]
+ )
+ def test_gate_skip_records_its_reason_on_the_report(
+ self, _name: str, state: str, has_report: bool, expected_reason: str | None
+ ) -> None:
+ report = None
+ if has_report:
+ report = ReviewReport.objects.for_team(self.team.id).create(
+ team=self.team, repository="PostHog/posthog", pr_number=123, pr_url="u"
+ )
+ metadata = _pr_metadata().model_copy(update={"author": "ghost", "state": state})
+ with (
+ patch(f"{_RESOLUTION}._installation_for", return_value=_mock_installation()),
+ patch(f"{_RESOLUTION}._fetch_pr_metadata", return_value=metadata),
+ ):
+ result = _prepare_run(
+ ResolveThreadsInput(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ acting_user_id=None,
+ owner="posthog",
+ repo="posthog",
+ pr_number=123,
+ )
+ )
+
+ assert isinstance(result, ResolutionRunResult)
+ stored = ReviewReportArtefact.objects.for_team(self.team.id).filter(type="note")
+ if report is None:
+ assert not stored.exists()
+ return
+ markers = run_outcome_markers(self.team.id, [str(report.id)])[str(report.id)]
+ assert [(m.stage, m.outcome, m.reason) for m in markers] == [("resolution", "skipped", expected_reason)]
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index e66623e73fbd..97a1c76163c2 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -12,7 +12,6 @@ from social_django.models import UserSocialAuth
from posthog.models import Team, User
-from products.review_hog.backend.api.reviews import IN_PROGRESS_STALE_AFTER
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
from products.review_hog.backend.reviewer.artefact_content import (
FindingOutcomeArtefact,
@@ -36,7 +35,11 @@ from products.review_hog.backend.reviewer.persistence import (
persist_perspective_selection,
persist_pr_snapshot,
)
-from products.review_hog.backend.reviewer.progress import RESOLUTION_RUN_NOTE_AUTHOR
+from products.review_hog.backend.reviewer.progress import (
+ IN_PROGRESS_STALE_AFTER,
+ RESOLUTION_RUN_NOTE_AUTHOR,
+ record_run_outcome,
+)
from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_SINGLE_AGENT
from products.review_hog.backend.temporal.heartbeat import ReviewActivityHeartbeater
from products.signals.backend.artefact_attribution import ArtefactAttribution
@@ -833,23 +836,40 @@ class TestRecentReviewsAPI(APIBaseTest):
assert (latest["status"], latest["total"], latest["fixed"], latest["needs_attention"]) == ("completed", 5, 4, 1)
assert latest["commits"] == ["good"]
- def test_dead_resolution_run_shows_where_it_stopped(self) -> None:
+ @parameterized.expand(
+ [
+ ("no_later_activity", None, "stopped", 1),
+ ("later_run_outcome_note", "outcome_note", "stopped", 1),
+ ("later_thread_verdict", "thread_verdict", "resolving", 2),
+ ]
+ )
+ def test_dead_resolution_run_shows_where_it_stopped(
+ self, _name: str, later_write: str | None, expected_status: str, expected_done: int
+ ) -> None:
# The silent-death mode: a resolution that dies partway used to leave no trace anywhere.
# With the run anchor present, no closing note, and activity past the staleness window, the
- # row must say where it stopped instead of nothing.
+ # row must say where it stopped instead of nothing. A later run outcome note records that a
+ # run ended, so it must not count as activity that revives the dead run. A fresh verdict is
+ # real activity, so that run is still resolving.
with time_machine.travel(timezone.now() - timedelta(hours=2), tick=False):
report = self._report(pr_number=5, acting_user=self.user, status=ReviewReport.Status.IDLE)
self._resolution_run(report, ["PRRT_1", "PRRT_2", "PRRT_3"])
self._thread_verdict(report, "PRRT_1", "fixed")
+ if later_write == "outcome_note":
+ record_run_outcome(
+ self.team.id, str(report.id), stage="resolution", outcome="skipped", reason="no_unresolved_threads"
+ )
+ elif later_write == "thread_verdict":
+ self._thread_verdict(report, "PRRT_2", "fixed")
row = self.client.get(self.url).json()["results"][0]
- assert row["in_progress"] is False
+ assert row["in_progress"] is (expected_status == "resolving")
assert row["resolution"] == {
- "resolution_status": "stopped",
- "done": 1,
+ "resolution_status": expected_status,
+ "done": expected_done,
"total": 3,
- "fixed": 1,
+ "fixed": expected_done,
"needs_attention": 0,
}
@@ -949,34 +969,39 @@ class TestRecentReviewsAPI(APIBaseTest):
assert rows[0]["in_progress"] is True
assert {r["pr_number"] for r in rows[1:]} <= set(range(1, 6))
- def test_outcome_artefact_does_not_revive_the_in_progress_spinner(self) -> None:
+ @parameterized.expand([("finding_outcome", False), ("turn_artefact", True)])
+ def test_only_turn_artefacts_keep_the_in_progress_spinner(self, later_write: str, expected: bool) -> None:
# `finding_outcome` is the one artefact written outside a turn: the sweep appends it after the
# PR merges, which can be long after the run ended. Status only leaves ACTIVE on a successful
# finalize, so a run that crashed before finalize stays ACTIVE forever and the staleness
# window is the only thing that retires its spinner. Counting the sweep's write as liveness
- # would restart that window and show a live row for a report with nothing running.
+ # would restart that window and show a live row for a report with nothing running. A fresh
+ # turn-written artefact is real progress and must still keep the row live.
# ACTIVE with a completed turn behind it (the dormant re-review shape): a first-turn ACTIVE
# report is listed only while it is in progress, so it could not show the difference.
report = self._report(pr_number=7, acting_user=self.user, status=ReviewReport.Status.ACTIVE)
ReviewReport.objects.for_team(self.team.id).filter(id=report.id).update(
updated_at=timezone.now() - IN_PROGRESS_STALE_AFTER - timedelta(minutes=5)
)
- ReviewReportArtefact.add_finding_outcome(
- team_id=self.team.id,
- report_id=str(report.id),
- content=FindingOutcomeArtefact(
- issue_key="r1:f.py:10:logic",
- run_index=1,
- outcome="ignored",
- method="no_signal",
- reviewed_head="base_sha",
- final_head="head_sha",
- ),
- attribution=ArtefactAttribution.system(),
- )
+ if later_write == "finding_outcome":
+ ReviewReportArtefact.add_finding_outcome(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ content=FindingOutcomeArtefact(
+ issue_key="r1:f.py:10:logic",
+ run_index=1,
+ outcome="ignored",
+ method="no_signal",
+ reviewed_head="base_sha",
+ final_head="head_sha",
+ ),
+ attribution=ArtefactAttribution.system(),
+ )
+ else:
+ self._thread_verdict(report, "PRRT_1", "fixed")
row = next(r for r in self.client.get(self.url).json()["results"] if r["pr_number"] == 7)
- assert row["in_progress"] is False
+ assert row["in_progress"] is expected
def test_perspective_stats_aggregate_latest_turns_per_scope(self) -> None:
# Effectiveness must aggregate each report's LATEST turn only and, on the default scope,
diff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.py
index d704f701238b..2fe354102ebc 100644
--- a/products/review_hog/backend/tests/test_status_comment.py
+++ b/products/review_hog/backend/tests/test_status_comment.py
@@ -15,6 +15,7 @@ from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRange
from products.review_hog.backend.reviewer.persistence import persist_findings, persist_verdict, upsert_review_report
+from products.review_hog.backend.reviewer.progress import run_outcome_markers
from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT
from products.review_hog.backend.reviewer.status_comment import (
RESOLUTION_SECTION_START,
@@ -661,13 +662,33 @@ class TestUpdateResolutionStatusComment(BaseTest):
class TestFailRun(BaseTest):
- def test_returns_the_report_to_rest_even_without_a_status_comment(self) -> None:
+ @parameterized.expand(
+ [
+ ("before_finalize", False, 1),
+ # Finalize already bumped run_count, so the dying publish belongs to that same turn.
+ ("in_publish_window", True, 1),
+ ]
+ )
+ def test_returns_the_report_to_rest_and_records_the_failed_turn(
+ self, _name: str, finalized: bool, expected_run_index: int
+ ) -> 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
+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
+ assert report.status == ReviewReport.Status.ACTIVE
+ report.head_sha = "a" * 40
+ if finalized:
+ report.run_count = 1
+ report.completed_head_sha = report.head_sha
+ report.save(update_fields=["head_sha", "run_count", "completed_head_sha"])
- _fail_run(self.team.id, report_id)
+ _fail_run(self.team.id, report_id, review_mode="flash")
- assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).status == ReviewReport.Status.IDLE
+ report.refresh_from_db()
+ assert report.status == ReviewReport.Status.IDLE
+ markers = run_outcome_markers(self.team.id, [report_id])[report_id]
+ assert [(m.outcome, m.reason, m.run_index, m.review_mode, m.head_sha) for m in markers] == [
+ ("failed", "review_failed", expected_run_index, "flash", report.head_sha)
+ ]