From 2ad31dabe8ca14326eb9b8b0c47b25e0b40e3765 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:16:10 +1300 Subject: [PATCH 1/2] feat(review): support exact additional rounds --- design/developer-workflows/pr-lifecycle.md | 2 +- dev-tools/pr_review/README.md | 2 + dev-tools/pr_review/cli.py | 7 + dev-tools/pr_review/controller.py | 47 +++- .../pr_review/sqlite_provider_imports.py | 2 + .../validation/test_pr_review_cli_runner.py | 23 ++ .../validation/test_pr_review_controller.py | 220 ++++++++++++++++++ .../test_pr_review_sqlite_provider_imports.py | 27 ++- 8 files changed, 313 insertions(+), 17 deletions(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 726f860a62..22b3009ac6 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -19,7 +19,7 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, - 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 ] [--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`). 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 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. - 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/README.md b/dev-tools/pr_review/README.md index e15fdb9227..3447df5d00 100644 --- a/dev-tools/pr_review/README.md +++ b/dev-tools/pr_review/README.md @@ -12,6 +12,8 @@ The output identifies the SQLite schema and writer build. The live shared cutove For a posted Hosted request, `dev-tools/pr-review wait hosted --pr --trigger-id ` watches only that saved trigger. `--poll-seconds` defaults to 30 and `--max-wait-minutes` to 90. It returns JSON and exit status 0 for an attributable completion, 3 for another terminal result, or 4 when the wait expires; it never posts a request, grants review credit, or retires the trigger. The caller must read the result and use `records sync-hosted --pr ` before adjudicating a completed review. A wait expiration leaves the underlying trigger unchanged. +To require exactly a chosen number of further completed attributable results on one channel, use `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --exact-additional-completed --reason ""`. Use `allocation renew` instead of `grant` to replace an existing allocation or human stop explicitly. The command records the existing minimum and maximum as the same positive number; it does not start a fresh taper streak. Earlier completed evidence remains historical, while a verifiable request already admitted at the decision remains in flight and consumes one result only if it later completes attributably. Failures, rate limits, and other non-counting results consume none. Discovery continues until all `N` results complete even if ordinary taper was already satisfied or becomes satisfied early, then closes at the exact cap while accepted findings and fixes remain mandatory obligations. + ### Manual Hosted adoption A human-posted Hosted CodeRabbit request can be incorporated without requesting another review: after the review completes, run `dev-tools/pr-review decide trigger-adopt-manual --pr --trigger-id --head `. This verifies the immutable public command, completed response, and current anchor before writing a private attribution record. A queued PR uses its reconciled stack parent; an off-queue PR uses its actual live base branch after matching the live base and head tips to their remote refs. Off-queue adoption leaves the configured review queue unchanged. The command does not post a GitHub comment, create a result checkpoint, or grant taper by itself; adjudicate findings and post the normal public Hosted checkpoint next. A moved head or ambiguous response is refused. diff --git a/dev-tools/pr_review/cli.py b/dev-tools/pr_review/cli.py index d2c828a5ed..e801cb7eac 100644 --- a/dev-tools/pr_review/cli.py +++ b/dev-tools/pr_review/cli.py @@ -408,6 +408,12 @@ def records_database(command: argparse.ArgumentParser) -> None: metavar="N", help="maximum additional completed attributable results after the decision", ) + allocation.add_argument( + "--exact-additional-completed", + type=_positive_int, + metavar="N", + help="require exactly N additional completed attributable results after the decision", + ) allocation.add_argument( "--fresh-taper", action="store_true", @@ -1662,6 +1668,7 @@ def record(current): checkpoint=args.checkpoint, min_additional_completed=args.min_additional_completed, max_additional_completed=args.max_additional_completed, + exact_additional_completed=args.exact_additional_completed, fresh_taper=args.fresh_taper, ), 0 if args.decide_command == "stop": diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 1faacac900..1ddfd072de 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -5607,6 +5607,7 @@ def decide_allocation( checkpoint: str | None = None, min_additional_completed: int | None = None, max_additional_completed: int | None = None, + exact_additional_completed: int | None = None, fresh_taper: bool = False, ) -> dict[str, Any]: """Grant, replace, or cancel a one-result or bounded review allocation.""" @@ -5623,6 +5624,22 @@ def decide_allocation( raise ControllerError("fresh taper selection must be boolean") if checkpoint is not None and (not isinstance(checkpoint, str) or not checkpoint.strip()): raise ControllerError("allocation baseline checkpoint must be a non-empty immutable identity") + if exact_additional_completed is not None and ( + isinstance(exact_additional_completed, bool) + or not isinstance(exact_additional_completed, int) + or exact_additional_completed <= 0 + ): + raise ControllerError("exact additional completed reviews must be a positive integer") + if exact_additional_completed is not None and ( + min_additional_completed is not None or max_additional_completed is not None + ): + raise ControllerError("exact additional completed reviews cannot be combined with minimum or maximum") + if exact_additional_completed is not None and fresh_taper: + raise ControllerError("exact additional completed reviews preserve the existing taper") + exact_replacement = exact_additional_completed is not None + if exact_replacement: + min_additional_completed = exact_additional_completed + max_additional_completed = exact_additional_completed if min_additional_completed is not None and ( isinstance(min_additional_completed, bool) or not isinstance(min_additional_completed, int) @@ -5706,10 +5723,26 @@ def provable_posted_hosted_request(value: Any) -> bool: and self._hosted_anchor_matches(value, pr, current) ) + def exact_in_flight_request(value: Any) -> bool: + if not exact_replacement or _field(value, "channel") not in (None, selected.value): + return False + if selected == policy.Channel.HOSTED: + return self._hosted_active_response_overlaps_cli( + value, + pr, + item.head, + current, + require_response_identity=True, + ) + return self._active_cli_review_overlaps_hosted(value, pr, current) + + def permitted_in_flight_request(value: Any) -> bool: + return exact_in_flight_request(value) if exact_replacement else provable_posted_hosted_request(value) + stop_evidence_checked = False if ( bounded_replacement - and not any(provable_posted_hosted_request(value) for value in history) + and not any(permitted_in_flight_request(value) for value in history) and ( prior_taper_complete or any( @@ -5749,7 +5782,7 @@ def provable_posted_hosted_request(value: Any) -> bool: and target.pr == pr and target.status == policy.ReviewStatus.JUDGMENT_REQUIRED ): - if not fresh_taper: + if not fresh_taper and not exact_replacement: raise ControllerError( "bounded Hosted allocation after a judgment-required taper must explicitly reopen fresh taper" ) @@ -5769,12 +5802,12 @@ def provable_posted_hosted_request(value: Any) -> bool: bounded_replacement and target.pr == pr and target.status == policy.ReviewStatus.HELD - and any(provable_posted_hosted_request(value) for value in history) + and any(permitted_in_flight_request(value) for value in history) ): raise elif bounded_replacement: assert previous is not None - if previous.stop_basis is not None: + if previous.stop_basis is not None and not exact_replacement: raise ControllerError("a stopped allocation cannot be renewed") if self._head_repository_problem(item): raise ControllerError(f"PR #{pr} has an unsupported head repository") @@ -5798,10 +5831,12 @@ def provable_posted_hosted_request(value: Any) -> bool: _field(value, flag) is True for flag in ("held", "unstable", "rate_limited", "unreconciled", "parent_moved", "over_ceiling") ) and _field(value, "head", "reviewed_head") in (None, "", item.head) - if blocked and not provable_posted_hosted_request(value): + if blocked and not permitted_in_flight_request(value): raise ControllerError("current review evidence is blocked; allocation cannot be promised") baseline = tuple( - _field(value, "checkpoint", "checkpoint_id") for value in history if _field(value, "correction") is not True + _field(value, "checkpoint", "checkpoint_id") + for value in history + if _field(value, "correction") is not True and not exact_in_flight_request(value) ) if any(not isinstance(value, str) or not value for value in baseline): raise ControllerError("existing review evidence lacks a checkpoint identity") diff --git a/dev-tools/pr_review/sqlite_provider_imports.py b/dev-tools/pr_review/sqlite_provider_imports.py index b1c2e34a09..a9ecbed963 100644 --- a/dev-tools/pr_review/sqlite_provider_imports.py +++ b/dev-tools/pr_review/sqlite_provider_imports.py @@ -433,6 +433,8 @@ def _import_reply_only_hosted_checkpoint( checkpoint, state.response_id, state.duration_seconds, + repo, + pr_number, captured_head, record, hosted_payload, diff --git a/dev-tools/validation/test_pr_review_cli_runner.py b/dev-tools/validation/test_pr_review_cli_runner.py index 2a1c58e2c2..dd2390bf27 100644 --- a/dev-tools/validation/test_pr_review_cli_runner.py +++ b/dev-tools/validation/test_pr_review_cli_runner.py @@ -101,6 +101,29 @@ def test_minimum_and_maximum_are_optional_without_a_pinned_checkpoint(self): self.assertIsNone(maximum_only.min_additional_completed) self.assertEqual(maximum_only.max_additional_completed, 3) + def test_exact_additional_completed_accepts_only_a_positive_integer(self): + common = [ + "decide", + "allocation", + "grant", + "--pr", + "2827", + "--channel", + "cli", + "--head", + HEAD, + "--reason", + "three more completed CLI rounds", + "--exact-additional-completed", + ] + + args = _parser().parse_args([*common, "3"]) + + self.assertEqual(args.exact_additional_completed, 3) + for invalid in ("0", "-1", "not-an-integer"): + with self.subTest(invalid=invalid), self.assertRaises(SystemExit): + _parser().parse_args([*common, invalid]) + 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 414a305672..5f794ee432 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3404,6 +3404,226 @@ def test_bounded_allocation_can_be_renewed_or_cancelled_explicitly(self): ) self.assertEqual(cancelled["allocations"], []) + def test_exact_allocation_maps_to_equal_bounds_and_replaces_a_stopped_allocation(self): + for channel in ("hosted", "cli"): + with self.subTest(channel=channel): + evidence = {(1, channel): [self.scope_timeline_evidence(channel=channel)]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel=channel, reason="human stopped ordinary discovery") + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="run exactly two more completed rounds", + ) + + self.assertEqual(renewed["allocation"]["min_additional_completed"], 2) + self.assertEqual(renewed["allocation"]["max_additional_completed"], 2) + self.assertIsNone(renewed["allocation"]["stop_basis"]) + self.assertFalse(renewed["allocation"].get("reopens_taper", False)) + + def test_exact_allocation_explicitly_replaces_an_exhausted_allocation(self): + evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline")]} + controller = self.grant_bounded_allocation(checkpoint="baseline", cap=1, minimum=1, evidence=evidence) + evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="exhausted-result")) + self.assertEqual(controller.status()["prs"][0]["allocations"]["hosted"]["remaining"], 0) + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=2, + reason="replace the exhausted tranche with exactly two more rounds", + ) + + self.assertEqual(renewed["progress"]["completed_count"], 0) + self.assertEqual(renewed["progress"]["remaining"], 2) + + def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fails(self): + for channel, terminal, same_checkpoint in ( + ("hosted", "completed", False), + ("cli", "completed", True), + ("cli", "failed", True), + ): + with self.subTest(channel=channel, terminal=terminal): + if channel == "hosted": + active = { + "pr": 1, + "head": HEAD_1, + "checkpoint": "trigger:45", + "trigger_id": 45, + "response_id": 46, + "state": "active", + "active_reservation": True, + "held": True, + "unstable": False, + "attributable": True, + "terminal": False, + "reason": HOSTED_ACTIVE_RESPONSE_REASON, + "anchor": { + "pr": 1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + }, + } + else: + active = { + "pr": 1, + "head": HEAD_1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + "checkpoint": "active-cli:run." + "a" * 32, + "active_review": True, + "held": True, + "current_lock_owner": True, + } + evidence = { + (1, channel): [ + self.scope_timeline_evidence(channel=channel), + active, + ] + } + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel=channel, reason="stop while the admitted request finishes") + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="retain the admitted request and complete exactly two rounds", + ) + self.assertEqual(renewed["progress"]["in_flight"], 1) + self.assertEqual(renewed["progress"]["used"], 0) + + if terminal == "completed": + replacement = self.allocation_evidence( + checkpoint=active["checkpoint"] if same_checkpoint else "completed-after-decision", + channel=channel, + ) + else: + replacement = self.allocation_evidence( + checkpoint=active["checkpoint"] if same_checkpoint else "failed-after-decision", + channel=channel, + completed=False, + attributable=False, + rate_limited=True, + ) + evidence[(1, channel)][1] = replacement + progress = controller.status()["prs"][0]["allocations"][channel] + + self.assertEqual(progress["used"], 1 if terminal == "completed" else 0) + self.assertEqual(progress["remaining"], 1 if terminal == "completed" else 2) + + def test_exact_allocation_rejects_unsupported_active_evidence_without_replacing_stop(self): + cases = { + "wrong-channel": {"channel": "hosted"}, + "wrong-pr": {"pr": 2}, + "moved-anchor": {"parent_head": HEAD_2}, + "ambiguous": {"unstable": True}, + } + for name, changed in cases.items(): + with self.subTest(name=name): + evidence = {(1, "cli"): [self.scope_timeline_evidence(channel="cli")]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel="cli", reason="retain the audited stop") + active = { + "pr": 1, + "head": HEAD_1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + "checkpoint": "active-cli:run." + "b" * 32, + "active_review": True, + "held": True, + "current_lock_owner": True, + **changed, + } + evidence[(1, "cli")].append(active) + stopped = controller.store.load() + + with self.assertRaises(ControllerError): + controller.decide_allocation( + action="renew", + pr=1, + channel="cli", + head=HEAD_1, + exact_additional_completed=2, + reason="unsupported active evidence must fail closed", + ) + + self.assertEqual(controller.store.load(), stopped) + + def test_exact_allocation_does_not_stop_at_existing_or_early_taper(self): + for channel, prior_count in (("hosted", 1), ("cli", 3)): + with self.subTest(channel=channel): + history = [ + self.allocation_evidence(checkpoint=f"prior-{index}", channel=channel) + for index in range(prior_count) + ] + history.append(self.scope_timeline_evidence(channel=channel)) + evidence = {(1, channel): history} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + + controller.decide_allocation( + action="grant", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="complete two rounds after ordinary taper", + ) + history.append(self.allocation_evidence(checkpoint="exact-first", channel=channel)) + first = controller.status()["prs"][0]["allocations"][channel] + self.assertEqual((first["status"], first["used"]), ("CAP_ACTIVE", 1)) + + history.append(self.allocation_evidence(checkpoint="exact-second", channel=channel)) + final = controller.status()["prs"][0]["allocations"][channel] + self.assertIn(final["status"], {"CAP_TAPERED", "CAP_AUDITED_STOP"}) + self.assertEqual((final["used"], final["remaining"]), (2, 0)) + + def test_exact_allocation_rejects_invalid_or_conflicting_values_without_mutation(self): + controller = self.make({1: pr(1, HEAD_1)}, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + original = controller.store.load() + + for exact, extra, message in ( + (0, {}, "positive integer"), + (-1, {}, "positive integer"), + (True, {}, "positive integer"), + (2, {"min_additional_completed": 1}, "cannot be combined"), + (2, {"max_additional_completed": 3}, "cannot be combined"), + (2, {"fresh_taper": True}, "preserve the existing taper"), + ): + with self.subTest(exact=exact, extra=extra), self.assertRaisesRegex(ControllerError, message): + controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=exact, + reason="invalid exact allocation", + **extra, + ) + self.assertEqual(controller.store.load(), original) + def test_bounded_dry_result_can_be_renewed_without_stop_authorization(self): evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline", channel="hosted")]} controller = self.grant_bounded_allocation( diff --git a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py index 4d5ae00892..01b3c3e287 100644 --- a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py +++ b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py @@ -806,17 +806,24 @@ def test_reply_only_zero_checkpoint_requires_exact_edited_trigger_reply(self) -> path.parent.mkdir(parents=True) path.write_text(json.dumps(record), encoding="utf-8") - imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( - self.records, - repo=REPO, - pr_number=PR, - checkpoint=checkpoint, - actor="reviewer", - common=self.common, - scope="broad", - hosted_payload=payload, - ) + proof_method = pr_review.runtime.LiveEvidence._hosted_zero_reply_proof + with patch.object( + pr_review.runtime.LiveEvidence, + "_hosted_zero_reply_proof", + wraps=proof_method, + ) as zero_reply_proof: + imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + actor="reviewer", + common=self.common, + scope="broad", + hosted_payload=payload, + ) + self.assertEqual(zero_reply_proof.call_args.args[3:5], (REPO, PR)) self.assertEqual(imported["provider_id"], "trigger:101") self.assertEqual(imported["counts"], {"found": 0, "accepted": 0, "routed": 0}) self.assertEqual(set(imported["archive_artifacts"]), {"hosted_comments", "hosted_review", "metadata"}) From 4c5e40e1a2a3ba36013114fbfbd6ca3ec20501d0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:28:55 +1300 Subject: [PATCH 2/2] fix(review): retain active Hosted allocation evidence --- dev-tools/pr_review/runtime.py | 3 ++ .../validation/test_pr_review_controller.py | 32 +++++++++++-------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 731730b2bf..1f96df1299 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1684,6 +1684,9 @@ def _current_hosted_history( observation["anchor"] = dict(anchor) if isinstance(anchor, Mapping) else None observation["trigger_id"] = state.trigger_comment_id observation["response_id"] = state.response_id + observation["state"] = state.state + observation["attributable"] = state.attributed + observation["terminal"] = state.terminal if state.state == "ambiguous" and not operational_only: terminal_observation = self._terminal_ambiguous_hosted_observation(pr, record, state, payload) if terminal_observation is not None: diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 5f794ee432..ed84bc8011 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3452,19 +3452,7 @@ def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fai ): with self.subTest(channel=channel, terminal=terminal): if channel == "hosted": - active = { - "pr": 1, - "head": HEAD_1, - "checkpoint": "trigger:45", - "trigger_id": 45, - "response_id": 46, - "state": "active", - "active_reservation": True, - "held": True, - "unstable": False, - "attributable": True, - "terminal": False, - "reason": HOSTED_ACTIVE_RESPONSE_REASON, + record = { "anchor": { "pr": 1, "child_head": HEAD_1, @@ -3472,8 +3460,24 @@ def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fai "parent_head": BASE, "merge_base": BASE, "patch_id": f"patch-{HEAD_1[:4]}", - }, + } } + state = SimpleNamespace( + state="active", + head_sha=HEAD_1, + trigger_comment_id=45, + response_id=46, + terminal=False, + attributed=True, + reason=HOSTED_ACTIVE_RESPONSE_REASON, + ) + live_evidence = LiveEvidence("owner/repo", LiveGitHub("owner/repo")) + with ( + patch.object(hosted, "current_trigger_record_paths", return_value=[Path("/trigger.json")]), + patch.object(hosted, "load_trigger_reservation", return_value=record), + patch.object(hosted, "trigger_state", return_value=state), + ): + active = live_evidence._current_hosted_history(1, HEAD_1, {}, set())[0] else: active = { "pr": 1,