Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions design/developer-workflows/pr-lifecycle.md

Large diffs are not rendered by default.

18 changes: 17 additions & 1 deletion dev-tools/pr_review/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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",
Expand Down
77 changes: 75 additions & 2 deletions dev-tools/pr_review/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
117 changes: 99 additions & 18 deletions dev-tools/pr_review/hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]:
Expand All @@ -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:
Expand All @@ -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")
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion dev-tools/pr_review/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions dev-tools/validation/test_pr_review_cli_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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(
[
Expand Down
Loading
Loading