diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index bc7c38ae69..84a2ae809e 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -13,13 +13,13 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, - Hosted taper is one completed, attributable zero-useful result for that PR; CLI taper is three consecutive such results for that PR. Results count across reviewed heads without a lineage, patch-equivalence, or current-head requirement. Once reached, taper is durable: later commits, bases, patches, fixes, or reconciliation do not erase it or automatically reopen the channel. An explicit human `reopen` judgment or `allocation grant|renew --fresh-taper` starts a fresh per-PR/channel streak at its decision boundary; earlier dry results remain visible but cannot satisfy the new streak. An ordinary bounded allocation does not reset completed taper by itself. An accepted allocated result breaks the active streak; later taper is evaluated after that result. Accepted findings and fixes remain mandatory holds. Identity checks may guard a new request but never queue advancement past a PR whose channel is complete or human-stopped. Invalid, duplicate, already-fixed-only, and other completed zero-useful results count; a literal `0/0` is unnecessary. Policy overrides remain explicit and are never inferred automatically. - Future Hosted and CLI checkpoints report `found / accepted / routed`. `found` is the provider's raw count, `accepted` is a valid fix owned by the reviewed PR, and `routed` is an observation assigned to another owner without adjudicating it for that owner. Only accepted findings extend source taper or require an in-PR fix before its next review. A route is informational on its source PR and creates no source warning, taper hold, review-selection hold, or merge hold; the destination owner judges it independently. Existing public counts and captures remain unchanged, and old checkpoints have an unknown routed count rather than an inferred zero or retroactive reclassification. - For each PR, the controller derives the expected effective parent as the nearest preceding unmerged configured PR, or the repository default base after all predecessors merge. The request records the PR number, child head, expected parent identity and exact parent head, merge-base SHA, and unique patch identity. Without `--force`, admission requires the live base and parent tip to match that identity, the parent to be an ancestor of the candidate, and every earlier adjacent link to be coherent; `PARENT_MOVED` and `UNRECONCILED` remain holds even when a merge base exists. `--force` may acknowledge a known topology or merge-readiness warning only while the PR and committed candidate remain exact, and admission rechecks for identity movement. When the provider's actual diff base/ref differs from the expected parent, retain the provider-observed base/ref with the forced attempt; do not describe the expected queue parent as the diff that was reviewed. The warning remains relevant to merge readiness. -- Reconciliation or an unproven candidate may block a new request only while that channel's policy remains incomplete; `--force` can acknowledge a known reconciliation warning when PR and committed candidate identity are certain, but cannot override candidate uncertainty or undo completed taper or an explicit human stop. A Hosted/CLI head mismatch alone does not require another review or judgment. Further review after completion or a stop requires an explicit human `reopen` decision or fresh-taper allocation. +- Reconciliation or an unproven candidate may block a new request only while that channel's policy remains incomplete; `--force` can acknowledge a known reconciliation warning when PR and committed candidate identity are certain, but cannot override candidate uncertainty or undo completed taper or an explicit human stop. A Hosted/CLI head mismatch alone does not require another review or judgment. Further review after completion or a stop requires an explicit human `reopen` decision, fresh-taper allocation, or exact additional-completed allocation through `allocation grant|renew` as described below. - When a coherent rebase or retarget leaves historical evidence anchored to the old parent, record the exact transition with `dev-tools/pr-review decide reconcile --pr --channel hosted|cli --checkpoint --prior-head --reason ""`. This records the ancestry transition without erasing completed taper or granting new review credit. The controller verifies the old attributable anchor and current branch, parent, ancestry, merge-base, and patch identities for that transition; the decision becomes invalid after any bound identity changes. - When historical evidence is readable but lacks the modern linked anchor required by `decide reconcile`, use `dev-tools/pr-review decide transition --pr --head --reason ""` to record the observed legacy records without inventing new checkpoints or spending review quota. The exact observations captured by that transition become non-counting policy history and cannot satisfy taper, even if a legacy record appears completed and attributable; newer independently attributable results remain counting. Active Hosted reservations and unresolved findings remain separate request or merge obligations. - If that exact legacy transition is followed by a fresh review and a later coherent fix head, reauthorize only the same immutable fingerprints with `dev-tools/pr-review decide transition --reauthorize --pr --head --reason ""`. The controller requires a prior transition, verifies every carried record again, and requires every other observation to be normal completed attributable anchored evidence; newer evidence remains counting and subject to ordinary reconciliation and judgment. A changed head without this explicit reauthorization remains blocked, and the command never creates a checkpoint or consumes review quota. - A single previously audited Hosted fingerprint that is absent from the complete current history may be retired only with `--reauthorize --retire-missing-hosted-fingerprint `. This requires the exact prior fingerprint, coherent current topology, complete available Hosted trigger records and paginated GitHub review/comment history, terminal and uniquely attributable responses, no active or unresolved reservation, and no unresolved actionable findings; any missing or ambiguous proof remains held. The fingerprint stays in the transition audit and remains non-counting if it later reappears. This decision never reconstructs evidence or creates a checkpoint and does not grant review, taper, finding-count, or merge-readiness credit. - Record an explicit channel judgment with `dev-tools/pr-review decide judgment retain|reopen --pr --channel hosted|cli --head --checkpoint --reason ""`. Retain confirms the verified equivalent patch for request and queue safety; reopen explicitly requires fresh review without deleting historical completed taper and resets the taper streak at the bound checkpoint. For CLI, a reopen may bind the latest complete modern checkpoint to a proven descendant live head, but carries no new review credit until later completed results arrive. A narrow channel policy override uses `dev-tools/pr-review decide policy --pr --head --checkpoint --hosted-zero-useful --reason ""` or `--cli-zero-useful ` (exactly one channel); it sets that channel's zero-useful completion count for the exact checkpoint. -- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--exact-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). `--exact-additional-completed N` is mutually exclusive with the separate bounds and `--fresh-taper`, and records `min=max=N`, so ordinary taper cannot stop discovery before all `N` results and the cap stops discovery immediately afterward. It preserves the existing taper rather than starting a fresh streak. Use `allocation renew --exact-additional-completed N` to replace an existing allocation or audited human stop explicitly. A verifiable request already admitted at the exact-allocation decision remains in flight and counts only when it completes attributably; ambiguous or unsupported active evidence is refused. Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. +- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--exact-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). `--exact-additional-completed N` is mutually exclusive with the separate bounds and `--fresh-taper`, and records `min=max=N`, so ordinary taper cannot stop discovery before all `N` results and the cap stops discovery immediately afterward. It preserves the existing taper rather than starting a fresh streak. Use `allocation renew --exact-additional-completed N` to replace an existing allocation or audited human stop explicitly. A verifiable request already admitted at the decision remains in flight and counts only when it completes attributably; pre-POST reservations, ambiguous evidence, failures, rate limits, and unsupported active evidence do not receive allocation credit. Recording an allowance does not clear request blockers: identity, exclusivity, finding, and attribution checks still apply at admission. Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. - Normal taper can finish before a maximum once the minimum is met. After any additional result with accepted findings, no next request is allowed until those findings, current/outdated threads, actionable summary findings, and fix publication/validation obligations are clear, even if capacity remains. Once the maximum is used, no further request is allowed for that PR/channel; a maximum stop is not taper and does not waive accepted findings or fixes. `status` and `evidence` expose the minimum, maximum, completed count, baseline identity, in-flight results, taper state, and controlling reason. When the maximum is exhausted, the controller derives an audited human-cap stop and advances that channel through its normal selector without a separate `decide stop`, subject to the active-review safety described below. Pending obligations remain source-owned and visible as `cap exhausted; findings pending`; this stop is not taper, current-head review, CI/Smoke proof, or merge readiness. A bounded allocation can be replaced explicitly with `allocation renew` and new bounds; `allocation cancel` removes it. Ordinary fixes never reset its completed count. - When the Overseer deliberately allocates one further completed review before deciding whether to continue, record it before the review with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --reason ""`. Completed-result counts belong to the PR and channel and survive later identity changes; rate limits, partial, duplicate, and unattributable results do not consume the allocation. Record a human decision to make no further requests with `dev-tools/pr-review decide stop --pr --channel hosted|cli --reason ""`. This audited PR/channel override bypasses the taper gate only for queue advancement; it is not taper completion or proof of review coverage, and it persists across head and parent changes. It requires no completed checkpoint, clean findings, idle provider, or coherent review topology. An already admitted CLI or Hosted run continues with its reservation, capture, attribution, and eventual findings intact; finishing that run does not clear the override. Stop recording and new-request admission share only the short state mutation boundary, while each provider keeps its execution exclusion. Optional `--head` and `--checkpoint` pins must match the observed identities; unavailable optional Git proof is recorded as absent, never fabricated. Existing ambiguity-retention and over-ceiling acknowledgment options record their specific evidence without granting review credit. Discovery can advance only when the same channel has no active provider run. Accepted fixes, pending captures and adjudication, attributable evidence, current and outdated threads, actionable summaries, required CI, runtime proof, ancestry, and merge safety remain independent obligations. A stop overrides taper only and does not manufacture a reviewed head or merge readiness. - For a channel that still needs review, targeting stops at the first held, unstable, unreconciled, over-ceiling, or judgment-blocked PR; it skips PRs whose channel has completed taper or an audited human stop. The narrow exception is a verified terminal, non-counting Hosted response: keep that PR incomplete and visible, but use the next coherent PR's Hosted window if one exists. Do not post another request on the ambiguous PR or grant it taper or merge credit; revisit its evidence or obtain an audited human stop before its merge handoff. Request-time identity and active-review checks still apply before any new request for an incomplete channel. A file-ceiling rejection requires a coherent topology decision; there is no normal incremental-review fallback. diff --git a/dev-tools/pr_review/cli.py b/dev-tools/pr_review/cli.py index e801cb7eac..8c52b61cd4 100644 --- a/dev-tools/pr_review/cli.py +++ b/dev-tools/pr_review/cli.py @@ -39,6 +39,22 @@ class CliError(RuntimeError): pass +class _CliArgumentParser(argparse.ArgumentParser): + def parse_args(self, args=None, namespace=None): + parsed = super().parse_args(args, namespace) + if ( + getattr(parsed, "command", None) == "decide" + and getattr(parsed, "decide_command", None) == "allocation" + and getattr(parsed, "exact_additional_completed", None) is not None + and ( + getattr(parsed, "min_additional_completed", None) is not None + or getattr(parsed, "max_additional_completed", None) is not None + ) + ): + self.error("--exact-additional-completed cannot be combined with min or max additional-completed bounds") + return parsed + + def _positive_int(value: str) -> int: try: parsed = int(value) @@ -72,7 +88,7 @@ def _source_fix_sha(value: str) -> str: def _parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog="dev-tools/pr-review") + parser = _CliArgumentParser(prog="dev-tools/pr-review") parser.add_argument( "--acceptance-fixture", metavar="JSON", diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index cc66f9ddd9..d6684acb47 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -1060,6 +1060,52 @@ def _hosted_active_response_overlaps_cli( and _field(observation, "terminal") is False ) + @staticmethod + def _hosted_awaiting_response_matches( + observation: Any, + expected_pr: int, + current_anchor: AnchorFacts | None, + ) -> bool: + """Verify a posted request awaiting acknowledgment without counting completion.""" + if current_anchor is None: + return False + trigger_id = _field(observation, "trigger_id") + observed_head = _field(observation, "head", "reviewed_head") + return ( + _field(observation, "state") == "awaiting_response" + and _field(observation, "posted") is True + and _field(observation, "reason") == "no attributable terminal response" + and _field(observation, "held") is True + and _field(observation, "active_reservation") is True + and _field(observation, "unstable") is not True + and _field(observation, "attributable") is True + and _field(observation, "terminal") is False + and _field(observation, "response_id") is None + and type(_field(observation, "pr")) is int + and _field(observation, "pr") == expected_pr + and type(trigger_id) is int + and trigger_id > 0 + and _field(observation, "checkpoint", "checkpoint_id") == f"trigger:{trigger_id}" + and isinstance(observed_head, str) + and observed_head.casefold() == current_anchor.child_head.casefold() + and not any( + _field(observation, flag) is True + for flag in ( + "rate_limited", + "terminal_ambiguous", + "unreconciled", + "parent_moved", + "over_ceiling", + "provisional", + "correction", + "non_counting", + "completed", + "actionable", + ) + ) + and ReviewController._hosted_anchor_matches(observation, expected_pr, current_anchor) + ) + @staticmethod def _active_cli_review_overlaps_hosted( observation: Any, @@ -3246,6 +3292,31 @@ def _bounded_allocation_evidence(allocation: ReviewAllocation, history: Sequence "in_flight": len(in_flight_ids), "error": "an in-flight review has an incomplete or changed stack anchor", } + if ( + allocation.channel == "hosted" + and ( + _field(value, "state") in {"awaiting_response", "ambiguous"} + or _field(value, "reason") == "no attributable terminal response" + ) + and not ReviewController._hosted_awaiting_response_matches( + value, + allocation.pr, + AnchorFacts( + allocation.pr, + active_head, + active_parent_identity, + active_parent_head, + active_merge_base, + active_patch_id, + ), + ) + ): + return { + "baseline": baseline, + "results": results, + "in_flight": len(in_flight_ids), + "error": "an awaiting Hosted request lacks verified posted identity", + } identity = _field(value, "trigger_id", "run_id", "reservation_id", "attempt_id") if identity is None and trigger_checkpoint is not None: identity = trigger_checkpoint.group(1) @@ -5797,13 +5868,15 @@ def admitted_in_flight_request(value: Any) -> bool: ): return False if selected == policy.Channel.HOSTED: - return self._hosted_active_response_overlaps_cli( + if self._hosted_active_response_overlaps_cli( value, pr, request_anchor.child_head, request_anchor, require_response_identity=True, - ) + ): + return True + return self._hosted_awaiting_response_matches(value, pr, request_anchor) return self._active_cli_review_overlaps_hosted(value, pr, request_anchor) baseline = tuple( diff --git a/dev-tools/pr_review/hosted.py b/dev-tools/pr_review/hosted.py index 1ec845af8c..de977a4d87 100644 --- a/dev-tools/pr_review/hosted.py +++ b/dev-tools/pr_review/hosted.py @@ -1542,6 +1542,8 @@ def _archived_completed_thread_bodies( repo: str, pr_number: int, head: str, + response_id: int, + response_created_at: datetime, record: Mapping[str, Any] | None, current_record_path: str | Path | None, ) -> dict[int, tuple[str, str]]: @@ -1559,28 +1561,32 @@ def _archived_completed_thread_bodies( or type(trigger_id) is not int or trigger_id <= 0 or trigger_at is None + or type(response_id) is not int + or response_id <= 0 or not isinstance(record.get("head_sha"), str) or record["head_sha"].casefold() != head.casefold() ): return {} - selected_record = Path(current_record_path) if current_record_path is not None else default_trigger_record_path( - repo, pr_number - ) - if selected_record.is_symlink(): - return {} - common = _trigger_record_common_for_path(selected_record, repo, pr_number) - if common is None: - return {} - selected_state = state_path(common) - if selected_state.is_symlink() or not selected_state.is_dir(): - return {} - database = sqlite_state_path(selected_state) try: + selected_record = ( + Path(current_record_path) + if current_record_path is not None + else default_trigger_record_path(repo, pr_number) + ) + if selected_record.is_symlink(): + return {} + common = _trigger_record_common_for_path(selected_record, repo, pr_number) + if common is None: + return {} + selected_state = state_path(common) + if selected_state.is_symlink() or not selected_state.is_dir(): + return {} + database = sqlite_state_path(selected_state) database_stat = database.stat(follow_symlinks=False) - except FileNotFoundError: - return {} - if database.is_symlink() or not stat.S_ISREG(database_stat.st_mode): + if database.is_symlink() or not stat.S_ISREG(database_stat.st_mode): + return {} + except (OSError, TypeError, ValueError): return {} try: @@ -1589,16 +1595,82 @@ def _archived_completed_thread_bodies( attempt_history = records.attempt_history(pr_number) current_history = [item for item in attempt_history if item.get("attempt_id") == current_attempt_id] current_head = current_attempt.get("candidate_sha") + request_metadata = current_attempt.get("metadata") + current_row = current_history[0] if len(current_history) == 1 else None + current_started_at = parse_timestamp(current_attempt.get("started_at")) + current_state = current_attempt.get("state") + current_trigger_id = current_row.get("trigger_id") if current_row is not None else None + current_response_id = current_row.get("provider_review_id") if current_row is not None else None + current_finished_at = parse_timestamp(current_attempt.get("finished_at")) if ( current_attempt.get("source_pr") != pr_number or current_attempt.get("channel") != "hosted" or not isinstance(current_head, str) or current_head.casefold() != head.casefold() - or len(current_history) != 1 - or current_history[0].get("trigger_id") != str(trigger_id) + or not isinstance(request_metadata, dict) + or not isinstance(request_metadata.get("repository"), str) + or request_metadata["repository"].casefold() != repo.casefold() + or not isinstance(response_created_at, datetime) + or current_started_at is None + or current_started_at > trigger_at + or current_row is None + or current_row.get("state") != current_state + or current_row.get("started_at") != current_attempt.get("started_at") + or current_row.get("finished_at") != current_attempt.get("finished_at") ): return {} + if current_state == "started": + if ( + current_trigger_id not in (None, str(trigger_id)) + or current_response_id is not None + or current_finished_at is not None + ): + return {} + if records.attempt_artifacts(current_attempt_id): + return {} + elif current_state == "completed": + if ( + current_trigger_id != str(trigger_id) + or current_response_id != str(response_id) + or current_finished_at is None + or current_finished_at < response_created_at + or current_attempt.get("run_id") not in (None, current_attempt_id) + ): + return {} + try: + current_artifacts = records.attempt_artifacts(current_attempt_id) + if not {"hosted_review", "hosted_comments", "metadata"} <= current_artifacts.keys(): + return {} + current_metadata = json.loads(current_artifacts["metadata"]) + except (TypeError, ValueError, json.JSONDecodeError): + return {} + current_observed_at = ( + parse_timestamp(current_metadata.get("observed_at")) if isinstance(current_metadata, dict) else None + ) + if ( + not isinstance(current_metadata, dict) + or current_metadata.get("state") != "completed" + or current_metadata.get("terminal") is not True + or current_metadata.get("attributable") is not True + or not isinstance(current_metadata.get("repository"), str) + or current_metadata["repository"].casefold() != repo.casefold() + or current_metadata.get("pull_request") != pr_number + or not isinstance(current_metadata.get("head_sha"), str) + or current_metadata["head_sha"].casefold() != head.casefold() + or type(current_metadata.get("trigger_id")) is not int + or str(current_metadata["trigger_id"]) != str(trigger_id) + or type(current_metadata.get("response_id")) is not int + or str(current_metadata["response_id"]) != str(response_id) + or current_observed_at is None + or current_observed_at != current_finished_at + ): + return {} + else: + # A terminal ambiguous or failed capture cannot be retroactively + # promoted by a later change in the public GitHub response. + return {} + candidates: dict[int, list[tuple[str, str]]] = {} for attempt in attempt_history: candidate_head = attempt.get("candidate_sha") @@ -1611,6 +1683,7 @@ def _archived_completed_thread_bodies( or not EXACT_SHA.fullmatch(candidate_head) or started_at is None or finished_at is None + or started_at > finished_at or finished_at >= trigger_at ): continue @@ -1685,6 +1758,7 @@ def _archived_completed_thread_bodies( review_submitted_at = parse_timestamp(matching_reviews[0].get("submittedAt")) if ( archived_trigger_at is None + or archived_trigger_at < started_at or archived_trigger_at > finished_at or review_submitted_at is None or review_submitted_at < archived_trigger_at @@ -1729,6 +1803,7 @@ def _addressed_thread_update_matches_archive( head: str, after: datetime, before: datetime | None, + response_id: int, archived_bodies: Mapping[int, tuple[str, str]], ) -> bool: """Accept only the exact known addressed footer appended to an archived finding.""" @@ -1752,6 +1827,8 @@ def _addressed_thread_update_matches_archive( or updated is None or updated <= after or (before is not None and updated >= before) + or type(response_id) is not int + or response_id <= 0 ): return False annotation = _ADDRESSED_COMMIT_ANNOTATION.search(body) @@ -2148,13 +2225,17 @@ def in_window(value: Any) -> bool | None: repo, pr_number, head, + response_id, + created, record, current_record_path, ) if isinstance(repo, str) and type(pr_number) is int and pr_number > 0 else {} ) - if _addressed_thread_update_matches_archive(item, head, after, before, archived_bodies): + if _addressed_thread_update_matches_archive( + item, head, after, before, response_id, archived_bodies + ): continue return False return True diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index aa8ef5369e..8c1d0c06af 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1682,9 +1682,10 @@ def _current_hosted_history( "active_reservation": state.state in {"active", "awaiting_response"} or operational_only, "reason": state.reason, } - if state.state == "active": + if state.state in {"active", "awaiting_response"}: anchor = record.get("anchor") observation["anchor"] = dict(anchor) if isinstance(anchor, Mapping) else None + observation["posted"] = record.get("status") == "posted" observation["trigger_id"] = state.trigger_comment_id observation["response_id"] = state.response_id observation["state"] = state.state diff --git a/dev-tools/validation/test_pr_review_cli_runner.py b/dev-tools/validation/test_pr_review_cli_runner.py index dd2390bf27..886bb9cc6c 100644 --- a/dev-tools/validation/test_pr_review_cli_runner.py +++ b/dev-tools/validation/test_pr_review_cli_runner.py @@ -17,6 +17,7 @@ DEV_TOOLS = Path(__file__).resolve().parents[1] sys.path.insert(0, str(DEV_TOOLS)) +from pr_review import cli as cli_module from pr_review import cli_attempts, cli_runner, evidence, github, hosted from pr_review.cli import _parser, _render from pr_review.cli_runner import ( @@ -124,6 +125,32 @@ def test_exact_additional_completed_accepts_only_a_positive_integer(self): with self.subTest(invalid=invalid), self.assertRaises(SystemExit): _parser().parse_args([*common, invalid]) + def test_exact_additional_completed_rejects_min_or_max_before_dispatch(self): + common = [ + "decide", + "allocation", + "grant", + "--pr", + "2827", + "--channel", + "cli", + "--head", + HEAD, + "--reason", + "exact additional review count", + ] + self.assertEqual( + _parser().parse_args( + [*common, "--min-additional-completed", "1", "--max-additional-completed", "4"] + ).min_additional_completed, + 1, + ) + for bound in ("--min-additional-completed", "--max-additional-completed"): + with self.subTest(bound=bound), patch.object(cli_module, "_dispatch") as dispatch: + with self.assertRaises(SystemExit): + cli_module.main([*common, "--exact-additional-completed", "3", bound, "2"]) + dispatch.assert_not_called() + def test_legacy_cancel_shape_needs_no_cap_replacement(self): args = _parser().parse_args( [ diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index ceb43df397..eea540d838 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -1364,6 +1364,203 @@ def test_allocation_is_promised_before_review_and_does_not_make_pr_complete(self self.assertNotEqual(result["channels"]["hosted"], "COMPLETE") self.assertEqual(controller.resolve_hosted_target().snapshot.number, 1) + def test_exact_allocation_reserves_posted_awaiting_hosted_trigger_until_completion(self): + for action in ("grant", "renew"): + with self.subTest(action=action): + timeline = self.scope_timeline_evidence() + evidence = { + (1, "hosted"): [self.allocation_evidence(checkpoint="allocation-baseline"), timeline] + } + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) + controller.set_stack([1]) + if action == "renew": + controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=2, + reason="initial two-result cap", + ) + + pending = { + "pr": 1, + "channel": "hosted", + "head": HEAD_1, + "checkpoint": "trigger:123", + "trigger_id": 123, + "response_id": None, + "state": "awaiting_response", + "posted": True, + "active_reservation": True, + "held": True, + "unstable": False, + "reason": "no attributable terminal response", + "attributable": True, + "terminal": False, + "anchor": hosted_anchor(), + } + evidence[(1, "hosted")].append(pending) + + result = controller.decide_allocation( + action=action, + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=1, + reason="reserve the exact posted request already awaiting its response", + ) + + self.assertEqual(result["progress"]["used"], 0) + self.assertEqual(result["progress"]["in_flight"], 1) + self.assertNotIn("trigger:123", result["allocation"]["baseline_checkpoints"]) + + evidence[(1, "hosted")] = [ + timeline, + self.allocation_evidence( + checkpoint="5847200187", + channel="hosted", + raw=0, + ) + ] + completed = controller.status()["prs"][0]["allocations"]["hosted"] + self.assertEqual(completed["completed_count"], 1) + self.assertEqual(completed["in_flight"], 0) + + def test_exact_awaiting_hosted_allocation_does_not_consume_failures_or_rate_limits(self): + for label, terminal in ( + ("failure", {"completed": False, "attributable": False, "failed": True}), + ("rate limit", {"completed": False, "attributable": False, "rate_limited": True}), + ): + with self.subTest(result=label): + timeline = self.scope_timeline_evidence() + pending = { + "pr": 1, + "channel": "hosted", + "head": HEAD_1, + "checkpoint": "trigger:123", + "trigger_id": 123, + "response_id": None, + "state": "awaiting_response", + "posted": True, + "active_reservation": True, + "held": True, + "unstable": False, + "reason": "no attributable terminal response", + "attributable": True, + "terminal": False, + "anchor": hosted_anchor(), + } + evidence = {(1, "hosted"): [pending, timeline]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) + controller.set_stack([1]) + controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=1, + reason="reserve one completion from the posted request", + ) + evidence[(1, "hosted")] = [ + timeline, + { + **self.allocation_evidence( + checkpoint="trigger:123", + channel="hosted", + anchored=False, + **terminal, + ), + "rate_limited": terminal.get("rate_limited", False), + } + ] + + progress = controller.status()["prs"][0]["allocations"]["hosted"] + + self.assertEqual(progress["completed_count"], 0) + self.assertEqual(progress["remaining"], 1) + + def test_exact_allocation_keeps_unsafe_or_ambiguous_awaiting_hosted_evidence_held(self): + valid = { + "pr": 1, + "channel": "hosted", + "head": HEAD_1, + "checkpoint": "trigger:123", + "trigger_id": 123, + "response_id": None, + "state": "awaiting_response", + "posted": True, + "active_reservation": True, + "held": True, + "unstable": False, + "reason": "no attributable terminal response", + "attributable": True, + "terminal": False, + "anchor": hosted_anchor(), + } + cases = ( + ("missing anchor", {key: value for key, value in valid.items() if key != "anchor"}), + ("unverified posted state", {**valid, "posted": False}), + ("incomplete anchor", {**valid, "anchor": {**hosted_anchor(), "patch_id": None}}), + ("mismatched head", {**valid, "head": HEAD_2}), + ("malformed trigger ID", {**valid, "trigger_id": "123"}), + ("response already present", {**valid, "response_id": 124}), + ( + "pre-POST reservation", + { + **valid, + "checkpoint": "trigger:pending", + "trigger_id": None, + "state": "ambiguous", + "reason": "trigger posting boundary is not verified", + "attributable": False, + "unstable": True, + }, + ), + ( + "ambiguous response", + { + **valid, + "state": "ambiguous", + "reason": "response attribution is ambiguous", + "attributable": False, + "terminal": True, + "unstable": True, + }, + ), + ("rate-limited", {**valid, "rate_limited": True}), + ) + for label, observation in cases: + with self.subTest(evidence=label): + timeline = self.scope_timeline_evidence() + evidence = {(1, "hosted"): [observation, timeline]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) + controller.set_stack([1]) + + result = controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=1, + reason="record allowance without accepting unsupported in-flight proof", + ) + + self.assertIn(observation["checkpoint"], result["allocation"]["baseline_checkpoints"]) + self.assertEqual(result["progress"]["in_flight"], 0) + snapshot = controller._bounded_allocation_evidence( + controller._state().allocations["1:hosted"], evidence[(1, "hosted")] + ) + self.assertEqual(snapshot["in_flight"], 0) + expected_error = ( + "an in-flight review has an incomplete or changed stack anchor" + if label in {"missing anchor", "incomplete anchor", "mismatched head"} + else "an awaiting Hosted request lacks verified posted identity" + ) + self.assertEqual(snapshot["error"], expected_error) + self.assertEqual(evidence[(1, "hosted")], [observation, timeline]) + self.assertNotEqual(controller._target("hosted", expected_pr=1).status, ReviewStatus.READY) + def test_default_one_result_allocation_requeues_completed_taper_without_resetting_it(self): history = [ self.allocation_evidence( diff --git a/dev-tools/validation/test_pr_review_evidence_hosted.py b/dev-tools/validation/test_pr_review_evidence_hosted.py index 7b7c91d573..d497035170 100644 --- a/dev-tools/validation/test_pr_review_evidence_hosted.py +++ b/dev-tools/validation/test_pr_review_evidence_hosted.py @@ -17,7 +17,7 @@ sys.path.insert(0, str(ROOT / "dev-tools")) from pr_review import cli as cli_module -from pr_review import cli_attempts, evidence, github, hosted, sqlite_review_records +from pr_review import cli_attempts, evidence, github, hosted, runtime, sqlite_review_records from pr_review.cli_runner import ReviewResult from pr_review.sqlite_finding_text import _safe_finding_detail from pr_review.sqlite_provider_imports import _cli_detail, _cli_finding_title, _cli_headline @@ -137,8 +137,8 @@ def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = T "observed_at": old_finished_at, } - state_dir = common / "firemud" / "pr-review-stack.json" - state_dir.mkdir(parents=True) + selected_state = common / "firemud" / "pr-review-stack.json" + selected_state.mkdir(parents=True) database = common / "firemud" / "pr-review-stack.sqlite3" SqliteStateStore(database).update(lambda state: state) records = SqliteReviewRecords(database) @@ -168,18 +168,7 @@ def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = T channel="hosted", candidate_sha=HEAD, started_at="2026-09-23T00:01:50Z", - ) - records.finish_attempt( - "current-hosted-attempt", - state="ambiguous", - finished_at="2026-09-23T00:02:08Z", - trigger_id="10", - provider_review_id="11", - artifacts={ - "hosted_review": "[]", - "hosted_comments": json.dumps({"comments": []}), - "metadata": json.dumps({"state": "ambiguous"}), - }, + metadata={"repository": REPO}, ) trigger = comment(10, "owner", hosted.FULL_COMMAND, trigger_at) @@ -1891,6 +1880,16 @@ def test_finished_reply_with_empty_complete_history_is_clean_completion(self): def test_finished_reply_accepts_only_exact_archived_addressed_thread_updates(self): with tempfile.TemporaryDirectory() as directory: payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + common = hosted._trigger_record_common_for_path(record_path, REPO, PR) + self.assertIsNotNone(common) + database = common / "firemud" / "pr-review-stack.sqlite3" + records = SqliteReviewRecords(database) + current_attempt = records.attempt("current-hosted-attempt") + self.assertEqual(current_attempt["state"], "started") + current_row = next( + item for item in records.attempt_history(PR) if item["attempt_id"] == "current-hosted-attempt" + ) + self.assertIsNone(current_row["trigger_id"]) state = hosted.trigger_state(REPO, PR, payload, record, record_path) @@ -1898,6 +1897,77 @@ def test_finished_reply_accepts_only_exact_archived_addressed_thread_updates(sel self.assertTrue(state.attributed) self.assertEqual(state.response_id, 11) + def test_runtime_zero_reply_proof_uses_custom_trigger_record_database(self): + with tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + checkpoint = evidence.Checkpoint( + comment_id=40, + created_at="2026-09-23T00:03:00Z", + type="Hosted", + raw_found=0, + accepted=0, + reviewed_sha=HEAD, + file_count=1, + correction=False, + updated_at=None, + run_id=None, + hosted_review_id=11, + ) + + proof = runtime.LiveEvidence._hosted_zero_reply_proof( + checkpoint, + 11, + None, + REPO, + PR, + HEAD, + record, + payload, + record_path, + ) + + self.assertIsNotNone(proof) + self.assertEqual(proof["review_id"], 11) + + def test_finished_reply_fails_closed_on_archive_lookup_filesystem_error(self): + with tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + with patch.object(hosted, "state_path", side_effect=PermissionError("state directory inaccessible")): + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "ambiguous") + self.assertFalse(state.attributed) + + def test_finished_reply_does_not_promote_ambiguous_or_mismatched_current_attempt(self): + cases = (("ambiguous", "10"), ("ambiguous", "99"), ("completed", "99")) + for attempt_state, trigger_id in cases: + with ( + self.subTest(state=attempt_state, trigger_id=trigger_id), + tempfile.TemporaryDirectory() as directory, + ): + payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + common = hosted._trigger_record_common_for_path(record_path, REPO, PR) + self.assertIsNotNone(common) + database = common / "firemud" / "pr-review-stack.sqlite3" + records = SqliteReviewRecords(database) + records.finish_attempt( + "current-hosted-attempt", + state=attempt_state, + finished_at="2026-09-23T00:02:08Z", + trigger_id=trigger_id, + provider_review_id="11", + artifacts={ + "hosted_review": "[]", + "hosted_comments": json.dumps({"comments": []}), + "metadata": json.dumps({"state": attempt_state}), + }, + ) + + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "ambiguous") + self.assertFalse(state.attributed) + def test_finished_reply_keeps_unproven_or_changed_thread_output_ambiguous(self): cases = ( ("unknown baseline", False, None), diff --git a/dev-tools/validation/test_pr_review_runtime.py b/dev-tools/validation/test_pr_review_runtime.py index 5bf701366a..52360d3d94 100644 --- a/dev-tools/validation/test_pr_review_runtime.py +++ b/dev-tools/validation/test_pr_review_runtime.py @@ -4552,6 +4552,48 @@ def test_active_hosted_observation_exposes_its_durable_anchor(self) -> None: self.assertEqual(observation["trigger_id"], 10) self.assertEqual(observation["response_id"], 11) + def test_posted_awaiting_hosted_observation_exposes_exact_trigger_and_durable_anchor(self) -> None: + now = datetime.now(timezone.utc).replace(microsecond=0) + trigger_at = (now - timedelta(minutes=1)).isoformat().replace("+00:00", "Z") + record = self._trigger_record(created=trigger_at) + state = SimpleNamespace( + trigger_comment_id=10, + response_id=None, + state="awaiting_response", + terminal=False, + attributed=True, + head_sha=HEAD, + reason="no attributable terminal response", + ) + payload = self._payload() + pull = payload["data"]["repository"]["pullRequest"] + pull.update({"number": 42, "baseRefName": "develop", "baseRefOid": BASE}) + snapshot = PullRequestSnapshot(42, "OPEN", "develop", BASE, HEAD, "feature", 1) + live = LiveGitHub("owner/repo") + with tempfile.TemporaryDirectory() as directory: + common = Path(directory) + record_path = hosted.default_trigger_record_path("owner/repo", 42, common) + record_path.parent.mkdir(parents=True) + record_path.write_text(json.dumps(record), encoding="utf-8") + with ( + patch.object(github, "fetch_pull_request", return_value=payload), + patch.object(live, "pull_request", return_value=snapshot), + patch.object(evidence, "git_common_dir", return_value=common), + patch.object(hosted, "trigger_state", return_value=state), + ): + history = list(LiveEvidence("owner/repo", live).history(42, "hosted")) + + observation = next(item for item in history if item.get("checkpoint") == "trigger:10") + self.assertEqual(observation["state"], "awaiting_response") + self.assertTrue(observation["posted"]) + self.assertTrue(observation["active_reservation"]) + self.assertTrue(observation["held"]) + self.assertTrue(observation["attributable"]) + self.assertFalse(observation["terminal"]) + self.assertEqual(observation["anchor"], record["anchor"]) + self.assertEqual(observation["trigger_id"], 10) + self.assertIsNone(observation["response_id"]) + def test_complete_audit_exposes_exact_active_hosted_response_identity(self) -> None: now = datetime.now(timezone.utc).replace(microsecond=0) trigger_at = (now - timedelta(minutes=2)).isoformat().replace("+00:00", "Z") diff --git a/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py b/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py index 684a54c4a1..aff748d301 100644 --- a/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py +++ b/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py @@ -1350,6 +1350,226 @@ def test_sync_backfills_missing_attempt_and_skips_linked_replay(self) -> None: self.assertTrue(replay["synced"], replay) self.assertTrue(replay["synced"][0]["idempotent_replay"]) + def test_sync_attributes_archived_addressed_thread_on_first_started_attempt_and_replays(self) -> None: + self._assert_sync_archived_addressed_thread_and_replay(partial_completed=False) + + def test_sync_recovers_unlinked_completed_addressed_thread_and_replays(self) -> None: + self._assert_sync_archived_addressed_thread_and_replay(partial_completed=True) + + def _assert_sync_archived_addressed_thread_and_replay(self, *, partial_completed: bool) -> None: + with tempfile.TemporaryDirectory() as directory: + common = Path(directory) / "git-common" + (common / "firemud" / "pr-review-stack.json").mkdir(parents=True) + records = self.new_records(common / "firemud" / "pr-review-stack.sqlite3") + old_head = "b" * 40 + old_attempt_id = "hosted-addressed-prior" + old_trigger_id = 801 + old_response_id = 802 + old_thread_comment_id = 803 + old_started_at = "2026-09-29T00:49:50Z" + old_trigger_at = "2026-09-29T00:50:00Z" + old_thread_created_at = "2026-09-29T00:50:30Z" + old_finished_at = "2026-09-29T00:51:00Z" + old_body = ( + "An archived CodeRabbit finding.\n\n" + "" + ) + old_review = { + "databaseId": old_response_id, + "author": {"login": "coderabbitai[bot]"}, + "body": "\nReviewing the archived candidate.", + "state": "COMMENTED", + "submittedAt": old_finished_at, + "commit": {"oid": old_head}, + } + old_trigger = self.trigger_comment( + trigger_id=old_trigger_id, + created_at=old_trigger_at, + ) + old_comments = { + "comments": [old_trigger], + "review_threads": [ + { + "comments": { + "nodes": [ + { + "databaseId": old_thread_comment_id, + "author": {"login": "coderabbitai[bot]"}, + "body": old_body, + "createdAt": old_thread_created_at, + "updatedAt": old_finished_at, + } + ] + } + } + ], + } + records.start_attempt( + attempt_id=old_attempt_id, + source_pr=PR, + channel="hosted", + candidate_sha=old_head, + started_at=old_started_at, + ) + records.finish_attempt( + old_attempt_id, + state="completed", + finished_at=old_finished_at, + trigger_id=str(old_trigger_id), + provider_review_id=str(old_response_id), + artifacts={ + "hosted_review": json.dumps([old_review]), + "hosted_comments": json.dumps(old_comments), + "metadata": json.dumps( + { + "state": "completed", + "terminal": True, + "attributable": True, + "repository": REPO, + "pull_request": PR, + "head_sha": old_head, + "trigger_id": old_trigger_id, + "response_id": old_response_id, + "observed_at": old_finished_at, + } + ), + }, + ) + + attempt_id = "hosted-sync-addressed-thread" + started_at = "2026-09-29T00:59:00Z" + trigger_at = "2026-09-29T01:00:00Z" + trigger = self.trigger_record( + trigger_id=901, + created_at=trigger_at, + posting_started_at=started_at, + attempt_id=attempt_id, + ) + record_path = self.write_trigger_record(common, trigger) + sqlite_hosted_capture.start_hosted_attempt( + records, + attempt_id=attempt_id, + source_pr=PR, + candidate_sha=HEAD, + started_at=started_at, + metadata={"repository": REPO}, + ) + summary = { + "databaseId": 903, + "author": {"login": "coderabbitai[bot]"}, + "body": ( + "No actionable comments were generated in the recent review.\n" + f"Reviewing files that changed from the base of the PR and between {old_head} and {HEAD}." + ), + "createdAt": "2026-09-29T00:59:30Z", + "updatedAt": "2026-09-29T01:02:00Z", + } + response = { + "databaseId": 902, + "author": {"login": "coderabbitai[bot]"}, + "body": "Full review finished.", + "createdAt": "2026-09-29T01:01:00Z", + "updatedAt": "2026-09-29T01:04:00Z", + "url": "https://github.example/owner/repo/pull/42#issuecomment-902", + } + addressed_thread_comment = { + "databaseId": old_thread_comment_id, + "author": {"login": "coderabbitai[bot]"}, + "body": f"{old_body}\n\n✅ Addressed in commits {'c' * 7} to {HEAD[:7]}", + "createdAt": old_thread_created_at, + "updatedAt": "2026-09-29T01:03:00Z", + } + payload = self.payload( + comments=[self.trigger_comment(trigger_id=901, created_at=trigger_at), summary, response], + review_threads=[{"comments": {"nodes": [addressed_thread_comment]}}], + ) + + if partial_completed: + pull = payload["data"]["repository"]["pullRequest"] + finished_at = "2026-09-29T01:04:00Z" + records.finish_attempt( + attempt_id, + state="completed", + finished_at=finished_at, + trigger_id="901", + provider_review_id="902", + artifacts={ + "hosted_review": json.dumps([]), + "hosted_comments": json.dumps( + { + "comments": pull["comments"]["nodes"], + "review_threads": pull["reviewThreads"]["nodes"], + } + ), + "metadata": json.dumps( + { + "state": "completed", + "terminal": True, + "attributable": True, + "repository": REPO, + "pull_request": PR, + "head_sha": HEAD, + "trigger_id": 901, + "response_id": 902, + "observed_at": finished_at, + } + ), + }, + ) + self.assertIsNone(records.attempt(attempt_id)["run_id"]) + original_attempt = sqlite_review_records.SqliteReviewRecords.attempt + + def conflicting_run_link(store, selected_attempt_id): + attempt = original_attempt(store, selected_attempt_id) + if selected_attempt_id == attempt_id: + return {**attempt, "run_id": "conflicting-source-run"} + return attempt + + with patch.object( + sqlite_review_records.SqliteReviewRecords, "attempt", autospec=True, side_effect=conflicting_run_link + ): + self.assertEqual( + hosted.trigger_state(REPO, PR, payload, trigger, record_path).state, + "ambiguous", + ) + + with patch.object(sqlite_hosted_capture.github, "fetch_pull_request", return_value=payload) as fetch: + if partial_completed: + fetch.side_effect = AssertionError("partial archive recovery must not fetch GitHub") + first = sqlite_hosted_capture.sync_hosted_pending(records, REPO, common=common, pr_number=PR) + + if partial_completed: + fetch.assert_not_called() + self.assertEqual(first["errors"], []) + self.assertTrue(first["synced"][0]["recovered_from_archive"], first) + self.assertEqual(records.attempt(attempt_id)["run_id"], attempt_id) + else: + fetch.assert_called_once_with(REPO, PR) + self.assertEqual(len(first["synced"]), 1, first) + self.assertEqual(first["synced"][0]["state"], "completed") + self.assertEqual(first["synced"][0]["counts"], {"found": 0, "accepted": 0, "routed": 0}) + self.assertEqual(records.attempt(attempt_id)["state"], "completed") + current_attempt = next( + item for item in records.attempt_history(PR) if item["attempt_id"] == attempt_id + ) + self.assertEqual(current_attempt["trigger_id"], "901") + self.assertEqual(current_attempt["provider_review_id"], "902") + self.assertEqual( + hosted.trigger_state(REPO, PR, payload, trigger, record_path).state, + "completed", + ) + + with patch.object( + sqlite_hosted_capture.github, + "fetch_pull_request", + side_effect=AssertionError("linked replay must not refetch GitHub"), + ) as replay_fetch: + replay = sqlite_hosted_capture.sync_hosted_pending(records, REPO, common=common, pr_number=PR) + + replay_fetch.assert_not_called() + self.assertEqual(len(replay["synced"]), 1, replay) + self.assertTrue(replay["synced"][0]["idempotent_replay"]) + def test_sync_keeps_active_pending_and_records_rate_limit(self) -> None: scenarios = ( (