diff --git a/.github/workflows/claude-review.yml b/.github/workflows/claude-review.yml index 7b58338..c26bc7c 100644 --- a/.github/workflows/claude-review.yml +++ b/.github/workflows/claude-review.yml @@ -25,6 +25,8 @@ # A pull request opened by the review agent is reviewed without a membership lookup. The request asks for a review # of the commits pushed, and of earlier ones not yet reviewed, with the whole pull request as context, and the # decision names the commit after the push. +# It is not sent at once: the settle job waits for pushes to settle (the settle-minutes input) and sends it only if +# no newer commit was pushed and the pull request is still open and ready, so a burst of pushes gets one review. name: Claude review on: @@ -46,6 +48,10 @@ on: description: The login of the review agent, the account mentioned in a comment command or requested as a reviewer, whose pull requests are reviewed without a membership lookup and whose comments and reviewer requests never request a review. type: string default: cipherstash-agent + settle-minutes: + description: How many minutes a Push request waits for pushes to settle before it is sent, a whole number from 0 (no wait) to 30. A newer push in that time skips it as superseded. On a private repository, each push to a ready pull request holds a runner for the wait. + type: number + default: 5 secrets: CLAUDE_ROUTINE_TOKEN: description: The code-review routine's bearer token. @@ -55,9 +61,16 @@ on: required: true outputs: # For a caller that checks what happened, such as this repository's self-test (.github/workflows/self-test.yml). + # The final decision: for a Push request, the settle job's, and for every other kind, the decide job's. A + # skipped job's output is empty. A settle job that ran but left no output, such as one whose runner was lost, + # gives the settle-check-failed skip, never the decide job's fire. decision: - description: The request decision, as JSON, such as {"decision":"skip","reason":"draft"}. - value: ${{ jobs.decide.outputs.decision }} + description: The final request decision, as JSON, such as {"decision":"skip","reason":"draft"}. For a Push request, it is the decision after the settle wait, such as {"decision":"skip","reason":"superseded"}. + value: ${{ fromJSON(jobs.decide.outputs.decision || '{}').decision == 'fire' && fromJSON(jobs.decide.outputs.decision || '{}').kind == 'push' && (jobs.settle.outputs.decision || '{"decision":"skip","reason":"settle-check-failed"}') || jobs.decide.outputs.decision }} + # The settle job's own decision, so a caller can tell a skip the settle wait made from one the decide job made. + settle-decision: + description: The settle job's decision, as JSON, for a Push request the decide job passed on, such as {"decision":"skip","reason":"superseded"}. Empty when the settle job did not run. + value: ${{ jobs.settle.outputs.decision }} sent: description: '"true" only when the routine trigger accepted the review request.' value: ${{ jobs.fire.outputs.sent }} @@ -214,11 +227,82 @@ jobs: echo "Claude review: skipped (decision-failed)" echo "Claude review: skipped (decision-failed)" >>"$GITHUB_STEP_SUMMARY" + # The settle wait: a Push request waits for pushes to settle, so a burst of pushes gets one review, of the last push. + # Runs only for a Push fire. After the wait it reads the pull request once, and passes the request on only if the pull + # request is still open, still ready and its head is still the commit after the push; otherwise it skips as + # superseded, draft or closed. Anything but a clear answer from GitHub is the settle-check-failed skip, with an error. + # It holds only pull-requests: read and no secrets, because it runs for minutes. It has no concurrency group, so a + # superseded request ends on its own as a green skip, never as a cancelled run, and a comment command or a requested + # reviewer never waits for it. The job itself stays green: its one step that can fail has continue-on-error, and + # its output falls back to the settle-check-failed skip. + settle: + needs: decide + if: fromJSON(needs.decide.outputs.decision).decision == 'fire' && fromJSON(needs.decide.outputs.decision).kind == 'push' + runs-on: ubuntu-latest + # The longest wait, 30 minutes, and the check's own time limits, with room to spare. + timeout-minutes: 40 + permissions: + pull-requests: read + outputs: + # The final decision for a Push request: the decide job's decision, passed on as it was written, or a skip. + decision: ${{ steps.check.outputs.decision || '{"decision":"skip","reason":"settle-check-failed"}' }} + env: + # Where the checkout step below puts this repository's step files. + WORKFLOW_FILES: ${{ github.workspace }}/.cipherstash-workflows + steps: + # The settle check's step file, checked out from this repository at the commit the caller pinned, the same way + # as in the decide job: only the steps/ directory, no credentials kept, and skipped if either value is empty. + - name: Check out the step files + id: checkout + if: job.workflow_repository != '' && job.workflow_sha != '' + continue-on-error: true + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: .cipherstash-workflows + sparse-checkout: | + /steps/ + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Wait for pushes to settle + id: check + continue-on-error: true + env: + # The job's own token, which can only read pull requests. + GITHUB_TOKEN: ${{ github.token }} + DECISION: ${{ needs.decide.outputs.decision }} + SETTLE_MINUTES: ${{ inputs.settle-minutes }} + CHECKOUT_OUTCOME: ${{ steps.checkout.outcome }} + # The settle check's file, from this repository's checkout. Python's standard library only (3.10 features), + # so nothing is installed; tests/test_settle.py runs this file. + STEP_FILE: ${{ env.WORKFLOW_FILES }}/steps/settle.py + # Without the checked-out files (the checkout failed, or settle.py or its helper module is missing), or if the + # file cannot run, the lines below write the settle-check-failed skip, an error and the summary line; a later + # write of the same output name wins. + run: | + if [[ "$CHECKOUT_OUTCOME" == success && -f "$STEP_FILE" && -f "${STEP_FILE%/*}/helpers.py" ]] && python3 "$STEP_FILE"; then + exit 0 + fi + echo 'decision={"decision":"skip","reason":"settle-check-failed"}' >>"$GITHUB_OUTPUT" + echo "::error::Could not check whether the push was superseded (checkout failed, or settle.py or helpers.py missing or broken); no review was requested" + echo "Claude review: skipped (settle-check-failed)" + echo "Claude review: skipped (settle-check-failed)" >>"$GITHUB_STEP_SUMMARY" + # Fires the routine trigger. It holds no permissions and sees only the decision: the event's free text reaches it only # as the decision's text, which the send step's json module places in the request body. + # A Push request fires only if the settle job passed it on; every other kind fires on the decide job's decision, as + # the settle job does not run for it. The condition starts with !cancelled() because GitHub skips a job whose + # condition has no status function when any job before it was skipped, as the settle job is for every other kind. fire: - needs: decide - if: fromJSON(needs.decide.outputs.decision).decision == 'fire' + needs: [decide, settle] + if: >- + ${{ !cancelled() + && needs.decide.result == 'success' + && fromJSON(needs.decide.outputs.decision).decision == 'fire' + && (fromJSON(needs.decide.outputs.decision).kind != 'push' + || (needs.settle.result == 'success' && fromJSON(needs.settle.outputs.decision || '{}').decision == 'fire')) }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: {} @@ -291,9 +375,15 @@ jobs: # reusable workflow's jobs cannot hold more than their caller. # The checkout is given no contents permission. This relies on this repository being public, as for the decide and # fire jobs, which hold no permissions at all; it is to be confirmed by the first live run (#20). + # The condition starts with !cancelled() for the same reason as the fire job's: the settle job before it is skipped + # for a comment command. react: needs: [decide, fire] - if: needs.fire.outputs.sent == 'true' && fromJSON(needs.decide.outputs.decision).react == true + if: >- + ${{ !cancelled() + && needs.fire.result == 'success' + && needs.fire.outputs.sent == 'true' + && fromJSON(needs.decide.outputs.decision).react == true }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 4e3094f..5c3f47f 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -12,10 +12,12 @@ # # Push reviews are off by default. To review the commits pushed to a pull request that is ready (not a draft), add # `synchronize` to the pull_request types below: `types: [opened, reopened, ready_for_review, review_requested, -# synchronize]`. Each push to a ready pull request whose author is a team member, or the review agent, then requests a -# review of the commits pushed, and of an earlier push's commits that got no review of their own. Pushes to drafts, -# pushes by bots, and pushes to bots' pull requests or to pull requests from forks are never reviewed. The pinned -# release must have Push reviews; an older one skips the event, so adding it early does no harm. +# synchronize]`. Each push to a ready pull request whose author is a team member, or the review agent, then waits for +# pushes to settle (5 minutes; pass `settle-minutes` in `with:` to change it, 0 for no wait) and requests a review of +# the commits pushed if no newer commit was pushed in that time, so a burst of pushes gets one review, which also +# covers the earlier pushes' commits. On a private repository each push holds a runner for the wait, about 5 billed +# minutes. Pushes to drafts, pushes by bots, and pushes to bots' pull requests or to pull requests from forks are never +# reviewed. The pinned release must have Push reviews; an older one skips the event, so adding it early does no harm. # # Needs, as organisation or repository settings: # secret CLAUDE_ROUTINE_TOKEN the code-review routine's bearer token diff --git a/.github/workflows/self-test.yml b/.github/workflows/self-test.yml index ca9ceed..43b5bb8 100644 --- a/.github/workflows/self-test.yml +++ b/.github/workflows/self-test.yml @@ -8,7 +8,8 @@ # commit that is running, not a pinned commit), with the stub's trigger id and token. The # verify job then fails if the review workflow decided not to request a review, naming the skip reason, if the request # was of the wrong kind for the event, or if it was not sent, and otherwise waits a few minutes for the stub's reply -# naming this run attempt. +# naming this run attempt. It passes a settle wait of 1 minute, so a run for a push stays quick; a push superseded by +# a newer push within that minute passes without a reply, because the newer push's own run is tested. # # A comment command, a new pull request comment whose first line is `@cipherstash-agent review`, runs the test too, # and the verify job also checks that the comment got the review workflow's 👀 reaction. A comment always @@ -139,6 +140,8 @@ jobs: with: routine-trigger-id: ${{ vars.CLAUDE_ROUTINE_INTEGRATION_TEST_TRIGGER_ID }} app-client-id: ${{ vars.CLAUDE_REVIEW_APP_CLIENT_ID }} + # A short settle wait, so a run for a push stays quick. Two pushes within a minute still test the superseded skip. + settle-minutes: 1 secrets: CLAUDE_ROUTINE_TOKEN: ${{ secrets.CLAUDE_ROUTINE_INTEGRATION_TEST_TOKEN }} CLAUDE_REVIEW_APP_PRIVATE_KEY: ${{ secrets.CLAUDE_REVIEW_APP_PRIVATE_KEY }} @@ -151,10 +154,12 @@ jobs: if: ${{ !cancelled() && needs.review.result != 'skipped' }} runs-on: ubuntu-latest timeout-minutes: 10 - # Reads the pull request's comments, and a comment's reactions. This repository is public, so the checkout below - # needs no contents permission, as the review workflow's own jobs show. + # Reads the pull request's comments, and a comment's reactions, and for a push the settle wait skipped, the pull + # request itself. This repository is public, so the checkout below needs no contents permission, as the review + # workflow's own jobs show. permissions: issues: read + pull-requests: read env: # Where the checkout step below puts this repository's step files, as in the review workflow's jobs. WORKFLOW_FILES: ${{ github.workspace }}/.cipherstash-workflows @@ -176,6 +181,13 @@ jobs: GITHUB_TOKEN: ${{ github.token }} DECISION: ${{ needs.review.outputs.decision }} SENT: ${{ needs.review.outputs.sent }} + # The settle job's own decision, empty when it did not run: a push's superseded, draft or closed skip passes + # only when the settle wait made it. + SETTLE_DECISION: ${{ needs.review.outputs.settle-decision }} + # For a push the settle wait skipped: the pull request to read and the commit after the push, so the step + # can check the pull request is in the state the skip names. Empty for other events. + PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }} + PUSHED_COMMIT: ${{ github.event.after }} # Which event started this run, so the step can check the request was of the kind that event makes. EVENT_NAME: ${{ github.event_name }} EVENT_ACTION: ${{ github.event.action }} diff --git a/CONTEXT.md b/CONTEXT.md index c6b4ebb..e02bf9b 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -21,9 +21,13 @@ The review request made by requesting a review from the review agent in a pull r _Avoid_: assigned reviewer **Push**: -The review request made when commits are pushed to a pull request that is ready (not a draft). It asks for a review of the commits pushed, and of an earlier push's commits that got no review of their own, with the whole pull request as context. A caller turns it on by listing the pull request `synchronize` event. +The review request made when commits are pushed to a pull request that is ready (not a draft). It asks for a review of the commits pushed, and of an earlier push's commits that got no review of their own, with the whole pull request as context. It is sent only after the settle wait. A caller turns it on by listing the pull request `synchronize` event. _Avoid_: sync, update, review on push +**Settle wait**: +The minutes a Push request waits before it is sent, so a burst of pushes gets one review (5 by default, set by the `settle-minutes` input). After the wait, the request is sent only if the pull request is still open and ready and no newer commit was pushed; otherwise it is skipped as superseded, draft or closed. The one review covers the earlier pushes' commits too, because a Push request asks for every change not yet reviewed. A newer push supersedes even when its own request is skipped, such as a bot's push; then no review is sent, and the commits are reviewed with the next push that is. +_Avoid_: debounce, delay, cooldown + **Team member**: A member of the GitHub team allowed to make review requests (by default `@cipherstash/developers`); nobody else can cause a review. _Avoid_: member, collaborator, maintainer diff --git a/README.md b/README.md index 7da5f26..34a6224 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,11 @@ It is off unless the caller lists the `synchronize` event (see [Turning on Push - Pushes to a draft are never reviewed, so work in progress can be pushed freely. Marking the draft ready still makes a Ready request, which reviews the whole pull request. - The request names the commit before the push and the commit after it, and asks for a review of the changes between them, with the whole pull request as context. It also asks for the earlier changes not yet reviewed: when the review agent's last review attestation on the pull request names a commit that is an ancestor of the commit before the push, the review starts there. So the commits of a push that got no review of its own, such as one replaced by a newer push before its review was requested, are reviewed with the next push. Only the review agent's attestations count, so another commenter cannot move the start. If the commit before the push is not an ancestor of the commit after it, as after a force push or a rebase, it asks for a review of the whole pull request instead. A push made while an earlier review is still running can repeat that review's changes, because that review has not posted its attestation yet. It asks to leave out changes that only came from merging the base branch in, such as GitHub's "Update branch" button. - A commit is named only when its id is exactly 40 lower-case hex characters. If either is missing or is not, the request asks for a review of the whole pull request. -- Every push fires at once. A push whose request is still waiting to be sent when a newer push arrives is replaced by it (see `concurrency` below), and its commits are reviewed with the newer push. There is no reaction and no instructions. +- It does not fire at once. It waits for pushes to settle: 5 minutes by default, set by the `settle-minutes` input. Then it reads the pull request once, and sends the request only if the pull request is still open, still ready, and its head is still the commit after the push. Otherwise it skips, with the reason `superseded` (a newer push came), `draft` or `closed`, and the newer push's own request goes on, unless that request is itself skipped. So a burst of pushes gets one review, of the last push. Each skip ends green, with the reason in the run's summary. +- That review also covers the commits of the earlier pushes in the burst, because a Push request also asks for an earlier push's commits not yet reviewed. +- A newer push supersedes an earlier one even when the newer push's own request is skipped, for example because a bot made it. Then no review is sent and both runs end green. The commits are reviewed with the next push that is sent, or at once with the comment command. +- A comment command or a requested reviewer never waits for a Push request, and is never cancelled by one. If both arrive within the wait, the pull request can get two reviews; each names the commit it reviewed. +- There is no reaction and no instructions. GitHub does not let you request a pull request's author as its reviewer. So on pull requests that `cipherstash-agent` opened, only Ready, Push and the comment command can request a review. @@ -112,9 +116,15 @@ on: Nothing else changes: the calling job's `if:` already lets every `pull_request` event through except requests for other reviewers, and no new permission is needed. The example caller does not list `synchronize`, and its header says how to add it. -Each push to a ready pull request then requests a review, so a busy branch gets a review for every push, and each review starts a Claude session and posts a review. +Each push to a ready pull request then waits for pushes to settle, and requests a review if no newer push came in the wait. Each review starts a Claude session and posts a review. The caller must pin a release that has Push reviews. An older release skips the event as `not-a-review-request`, so adding it early does no harm. +To change the settle wait, pass `settle-minutes`, a whole number from 0 to 30, in the calling job's `with:`. +A shorter wait reviews sooner but batches fewer pushes. A wait of 0 checks the pull request at once, so almost every push gets its own review. + +The wait costs runner time. On a public repository, runner minutes are free. +On a private repository, each push to a ready pull request holds a runner for the wait, so about 5 billed minutes per push at the default, whether or not the push is then reviewed. + GitHub runs `issue_comment` workflows from the repository's default branch, not from the pull request's branch. So the comment command works only once the caller is merged into the default branch. A pull request that adds the caller can test the Ready path and the requested reviewer, but not the comment command. @@ -139,22 +149,25 @@ The workflow uses it to get a short-lived token and look up whether the requeste | `team` | no | `developers` | The slug of the team, in the calling repository's organisation, whose members may request a review. | | `app-client-id` | yes | | The membership GitHub App's client ID, usually `vars.CLAUDE_REVIEW_APP_CLIENT_ID`. | | `review-agent` | no | `cipherstash-agent` | The login of the review agent. | +| `settle-minutes` | no | `5` | How many minutes a Push request waits for pushes to settle, a whole number from 0 (no wait) to 30. Any other value skips every Push request with `settle-check-failed`. On a private repository, each push holds a runner for the wait. | Both secrets, `CLAUDE_ROUTINE_TOKEN` and `CLAUDE_REVIEW_APP_PRIVATE_KEY`, are required and must be passed explicitly, as the example does. -The workflow has two outputs, for a caller that checks what happened, such as this repository's [self-test](#self-test): +The workflow has three outputs, for a caller that checks what happened, such as this repository's [self-test](#self-test): | Output | What it is | | --- | --- | -| `decision` | The request decision, as JSON, such as `{"decision":"skip","reason":"draft"}`. See [Output](#output). | +| `decision` | The final request decision, as JSON, such as `{"decision":"skip","reason":"draft"}`. See [Output](#output). For a Push request, it is the decision after the settle wait, such as `{"decision":"skip","reason":"superseded"}`. | +| `settle-decision` | The settle job's decision, as JSON, for a Push request the decide job passed on to the settle wait; otherwise empty. A skip in `decision` that matches it was made by the settle wait. | | `sent` | `true` only when the routine trigger accepted the review request; otherwise empty. | ### What a run shows -A run has up to three jobs: +A run has up to four jobs: -- `decide` reads the event and decides. It writes a one-line summary, such as `Claude review: skipped (draft)`, to the run's summary page. A line break in a reason is flattened to a space, so a reason cannot start a workflow command. It does not fail: every step that can fail is allowed to, and the decision then becomes a skip with the reason `decision-failed`. -- `fire` sends the request to the routine trigger. It runs only when `decide` decided to fire. It sends the request once, with no retry, and does not follow a redirect. Only a `2xx` answer counts as sent. A failed request shows as a failed step with an error, but the job and the check stay green. The error says what is known about the request: +- `decide` reads the event and decides. It writes a one-line summary, such as `Claude review: skipped (draft)`, to the run's summary page. A line break in a reason is flattened to a space, so a reason cannot start a workflow command. It does not fail: every step that can fail is allowed to, and the decision then becomes a skip with the reason `decision-failed`. For a Push request, its line says `Claude review: waiting for pushes to settle (push, ...)`, and `settle` writes the final one. +- `settle` is the settle wait. It runs only for a Push request that `decide` decided to fire. It waits `settle-minutes`, then reads the pull request once with the job's own token, with no retry and without following a redirect. It passes the request on if the pull request is still open, still ready and its head is still the commit after the push, and writes `Claude review: requested (push, ...)`. Otherwise it writes the skip, such as `Claude review: skipped (superseded)`. Anything but a clear answer from GitHub is the skip `settle-check-failed`, with an error. It does not fail, and it is never cancelled: it has no concurrency group, so a superseded request ends on its own as a green skip. +- `fire` sends the request to the routine trigger. It runs only when `decide` decided to fire and, for a Push request, `settle` passed it on. It sends the request once, with no retry, and does not follow a redirect. Only a `2xx` answer counts as sent. A failed request shows as a failed step with an error, but the job and the check stay green. The error says what is known about the request: - `Could not reach the routine trigger (); no review was requested`: the connection was refused, the name did not resolve, or another failure came before the request went out. A re-run is safe. - `The routine trigger did not answer in time (); the request may have been received, so check for a review before re-running`: no answer within the time limit. - `The routine trigger dropped the connection (); the request may have been received, so check for a review before re-running`: the connection closed after the request was sent. In both of these cases the routine may already have accepted the request, so a re-run could review twice. @@ -164,6 +177,7 @@ A run has up to three jobs: If the job could not check out its step file, no reaction is added, and the run shows a warning, but the check stays green. A failed checkout also prints its own error annotation, which is not a red check. `decide` and `fire` hold no permissions. +`settle` holds only `pull-requests: read`, and no secrets, because it runs for minutes. `react` holds only `issues: write` and `pull-requests: write`. GitHub documents `issues: write` as the permission for adding a reaction to an issue or pull request comment, but on a pull request's comment it refused a token with only that (HTTP 403), so the job also holds `pull-requests: write`. For each pull request there are two queues. Ready, comment command and requested-reviewer requests share one, and Push requests have the other. Only one `fire` runs at a time in each queue: a second waits rather than cancelling the first. If a third arrives while the second is still waiting, GitHub's concurrency rules replace the second with it, and the replaced run sends nothing, and its `fire` job shows as cancelled. This is because each queue uses `cancel-in-progress: false`, which keeps only one waiting run. The running one is never cancelled, and the newest request is the one that waits. @@ -231,8 +245,10 @@ Exactly one of: | --- | --- | | `not-a-review-request` | The event is not a review request, or has no author, comment author or sender to act as the requester (a payload whose `user` or `sender` is `null`). For example a pull request labelled or edited, a comment on an issue rather than a pull request, an edited or deleted comment, or a review requested from someone other than the review agent or from a team. | | `not-a-command` | A new pull request comment whose first line is not a comment command. | -| `closed` | The request is on a closed pull request, which includes a merged one. Checked before the requester checks, so no membership lookup is made. A comment is checked for the command first. | -| `draft` | The pull request is a draft. Only Ready and Push skip drafts. | +| `closed` | The request is on a closed pull request, which includes a merged one. Checked before the requester checks, so no membership lookup is made. A comment is checked for the command first. For Push, also when the pull request was closed during the settle wait. | +| `draft` | The pull request is a draft. Only Ready and Push skip drafts. For Push, also when the pull request was made a draft during the settle wait. | +| `superseded` | Push only: a newer commit was pushed during the settle wait, so the newer push's own request goes on instead, unless it is itself skipped, such as a bot's push. Ends green. | +| `settle-check-failed` | Push only: after the settle wait, whether the push was superseded could not be checked. GitHub could not be reached within 30 seconds, answered with an error status or a redirect, or gave an answer that is malformed or larger than 1 MiB; or the `settle-minutes` input is not a whole number from 0 to 30; or the `settle` job could not check out or run its step file. The request is not sent, and the run shows an error. | | `bot` | The requester is a bot. For Push, the pull request's author or the person who pushed is a bot. No membership lookup is made. | | `review-agent` | The requester is the review agent. No membership lookup is made. Ready and Push do not skip this: they review the agent's own pull requests. | | `fork` | The pull request comes from a fork, or from a fork that was deleted. Comment commands are not skipped for this. | @@ -252,17 +268,19 @@ The code for these steps is in the `steps/` directory: | --- | --- | | `steps/lookup.py` | The membership lookup, in the `decide` job. | | `steps/report.py` | The last step of the `decide` job. It passes on the decision, or the `decision-failed` skip, and writes the summary line. | +| `steps/settle.py` | The settle wait's check, in the `settle` job. | | `steps/fire.py` | The request to the routine trigger, in the `fire` job. | | `steps/react.py` | The 👀 reaction, in the `react` job. | | `steps/verify.py` | The [self-test](#self-test)'s check, in the `verify` job of `.github/workflows/self-test.yml`. It is not part of the reusable workflow. | | `steps/helpers.py` | Code every step shares: sending one request within the time limits without following a redirect, GitHub API headers, annotations, step outputs and hiding a token. | The `decide` job checks out `steps/` with the request decision, as described above. -The `fire` and `react` jobs check out `steps/` in the same way, because a job cannot see another job's files. +The `settle`, `fire` and `react` jobs check out `steps/` in the same way, because a job cannot see another job's files. Each of these checkouts is the step that comes first in its job, and a test checks that they all use the same settings. Each job names its checkout in its `env` as `WORKFLOW_FILES`. Each Python step names its file there in its `env` as `STEP_FILE`, and its short `bash` script runs that file with the runner's `python3`. If the report's file was not checked out, the step still writes the `decision-failed` skip, an error and the summary line by itself. +If the settle check's file or the helper module was not checked out, or cannot run, the step writes the `settle-check-failed` skip, an error and the summary line by itself. If the routine call's file was not checked out, the step sends nothing and shows an error. If the reaction's file or the helper module was not checked out, or the helper module cannot be loaded, the step adds no reaction and shows a warning. @@ -315,6 +333,9 @@ The stub only posts a comment saying it received the request, so a test run is f 3. The stub posts a comment on the pull request, echoing the attempt's link. 4. The `verify` job checks the review workflow's decision. The request must be a Ready request when the pull request was opened, reopened or marked ready, a Push request when commits were pushed, and a requested-reviewer request when a review was requested. If it decided to request a review of the right kind and sent the request, the job reads the pull request's comments every 15 seconds, for up to 5 minutes, until it finds a comment that contains `integration-test: received` and this attempt's link. Only a comment posted by the stub routine's account, `cipherstash-agent` (the `REPLY_AUTHOR` setting in the workflow; the login is compared without regard to case), counts, so someone else cannot pass the test by posting the marker on a public pull request. The comment author's standing in the repository (`author_association`) is not used, because the job's token may see a different standing for an account with private organisation membership. It then shows the reply, and its author, in a notice and in the run's summary. +The self-test passes a settle wait of 1 minute, so a run for a push stays quick. +If a newer push comes within that minute, the earlier push's run passes without a reply: the review workflow skips it as `superseded`, and the `verify` job says so in a notice, `Push not reviewed`, and in the run's summary. The newer push's run is the one that is tested. So two pushes within a minute get one stub reply, for the second push. A push whose pull request is made a draft or closed during the wait passes the same way, with the reason `draft` or `closed`. + The test is skipped, and the `skipped` job says why in a notice, for: - drafts, when they are opened or reopened. Marking the draft ready for review, or requesting a review from `cipherstash-agent`, runs the test. The review workflow takes a requested reviewer on a draft, so the test does too. @@ -483,11 +504,11 @@ Every Python step runs from a file in `steps/`, so none keeps its own copy of th To add a new Python step: -1. Write it as a file in `steps/`, importing what it needs from `steps/helpers.py`. Give it a name that is not a standard library module's, such as `notify.py` rather than `email.py`: a test checks this. Give every function type hints, add the module to the list of step files in `pyproject.toml` (see [Linting and type checking](#linting-and-type-checking)), and add the step to the exact set asserted in `tests/test_python_steps.py` (`test_the_lookup_the_report_the_routine_call_and_the_reaction_run_from_files`). +1. Write it as a file in `steps/`, importing what it needs from `steps/helpers.py`. Give it a name that is not a standard library module's, such as `notify.py` rather than `email.py`: a test checks this. Give every function type hints, add the module to the list of step files in `pyproject.toml` (see [Linting and type checking](#linting-and-type-checking)), and add the step to the exact set asserted in `tests/test_python_steps.py` (`test_the_lookup_the_report_the_settle_check_the_routine_call_and_the_reaction_run_from_files`). 2. In the workflow, give the step an `id`, its file as `STEP_FILE` in its `env`, and a `bash` script that runs the file, or does something safe if the file is missing. If its job has no checkout of this repository yet, copy the `checkout` step from the `fire` job to the start of the job. 3. Add `tests/test_.py`, running the file with `run_step`, and the `bash` script with `run_step_as_written`. -`tests/test_decision_file.py` checks that each file the workflow runs from its checkout exists in this repository and is included in the checkout of its own job, and that the `decide`, `fire` and `react` jobs check out this repository in the same way. So a renamed file fails the tests rather than every run. +`tests/test_decision_file.py` checks that each file the workflow runs from its checkout exists in this repository and is included in the checkout of its own job, and that the `decide`, `settle`, `fire` and `react` jobs check out this repository in the same way. So a renamed file fails the tests rather than every run. ### Linting and type checking diff --git a/examples/claude-review.yml b/examples/claude-review.yml index 4e3094f..5c3f47f 100644 --- a/examples/claude-review.yml +++ b/examples/claude-review.yml @@ -12,10 +12,12 @@ # # Push reviews are off by default. To review the commits pushed to a pull request that is ready (not a draft), add # `synchronize` to the pull_request types below: `types: [opened, reopened, ready_for_review, review_requested, -# synchronize]`. Each push to a ready pull request whose author is a team member, or the review agent, then requests a -# review of the commits pushed, and of an earlier push's commits that got no review of their own. Pushes to drafts, -# pushes by bots, and pushes to bots' pull requests or to pull requests from forks are never reviewed. The pinned -# release must have Push reviews; an older one skips the event, so adding it early does no harm. +# synchronize]`. Each push to a ready pull request whose author is a team member, or the review agent, then waits for +# pushes to settle (5 minutes; pass `settle-minutes` in `with:` to change it, 0 for no wait) and requests a review of +# the commits pushed if no newer commit was pushed in that time, so a burst of pushes gets one review, which also +# covers the earlier pushes' commits. On a private repository each push holds a runner for the wait, about 5 billed +# minutes. Pushes to drafts, pushes by bots, and pushes to bots' pull requests or to pull requests from forks are never +# reviewed. The pinned release must have Push reviews; an older one skips the event, so adding it early does no harm. # # Needs, as organisation or repository settings: # secret CLAUDE_ROUTINE_TOKEN the code-review routine's bearer token diff --git a/pyproject.toml b/pyproject.toml index 17e364a..cbaf7b4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,6 +50,8 @@ module = [ "test_python_steps", "test_report", "test_self_test", + "test_settle", + "test_settle_job", "test_verify", ] disallow_untyped_defs = false diff --git a/steps/helpers.py b/steps/helpers.py index 6ec6ce7..5877715 100644 --- a/steps/helpers.py +++ b/steps/helpers.py @@ -9,6 +9,7 @@ import contextlib import http.client +import json import os import signal import urllib.error @@ -56,6 +57,34 @@ def output(name: str, value: str) -> None: file.write(f"{name}<<{delimiter}\n{value}\n{delimiter}\n") +def text(value: object) -> str: + # As jq's string interpolation: a string as it is, anything else as JSON. + return value if isinstance(value, str) else json.dumps(value) + + +def summary(decision: dict[str, Any], requested: str = "requested") -> str: + """The run summary's line for a finished decision: a fire says what was requested (or, with requested, what is + happening to the request), and a skip names its reason.""" + if decision.get("decision") == "fire": + pull_request = decision.get("pull_request") + number = pull_request.get("number") if isinstance(pull_request, dict) else None + line = ( + f"Claude review: {requested} ({text(decision.get('kind'))}, by @{text(decision.get('requester'))}, " + f"pull request #{text(number)})" + ) + else: + line = f"Claude review: skipped ({text(decision.get('reason'))})" + # One line, whatever the decision holds, so it cannot start a workflow command. + return line.replace("\r", " ").replace("\n", " ") + + +def report_summary(line: str) -> None: + """Prints the run summary's line and adds it to the job summary.""" + print(line, flush=True) + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as file: + file.write(line + "\n") + + def redacted(text: str, token: str) -> str: """text with every copy of token taken out, in case an answer repeats the token it was sent.""" return text.replace(token, "[token]") if token else text diff --git a/steps/report.py b/steps/report.py index 69a7777..6ef25a4 100644 --- a/steps/report.py +++ b/steps/report.py @@ -1,7 +1,8 @@ """The decide job's last step: always leaves the fire job a finished decision, and writes the run's summary line. It writes the "decision-failed" skip first, so that if anything below breaks, that skip is what the fire job sees; the -valid decision then replaces it. +valid decision then replaces it. For a Push fire, the summary line says the request is waiting for pushes to settle: +the settle job decides whether it is sent, and writes that line. Inputs, all environment variables: FIRST and SECOND (the decisions before and after the membership lookup) and the runner's GITHUB_OUTPUT and GITHUB_STEP_SUMMARY. @@ -12,7 +13,7 @@ import os from typing import Any -from helpers import error, output +from helpers import error, output, report_summary, summary FAILED = '{"decision":"skip","reason":"decision-failed"}' @@ -28,25 +29,6 @@ def finished(value: str) -> dict[str, Any] | None: return None -def text(value: object) -> str: - # As jq's string interpolation: a string as it is, anything else as JSON. - return value if isinstance(value, str) else json.dumps(value) - - -def summary(decision: dict[str, Any]) -> str: - if decision.get("decision") == "fire": - pull_request = decision.get("pull_request") - number = pull_request.get("number") if isinstance(pull_request, dict) else None - line = ( - f"Claude review: requested ({text(decision.get('kind'))}, by @{text(decision.get('requester'))}, " - f"pull request #{text(number)})" - ) - else: - line = f"Claude review: skipped ({text(decision.get('reason'))})" - # One line, whatever the decision holds, so it cannot start a workflow command. - return line.replace("\r", " ").replace("\n", " ") - - try: output("decision", FAILED) value = os.environ.get("SECOND") or os.environ.get("FIRST") or "" @@ -58,10 +40,9 @@ def summary(decision: dict[str, Any]) -> str: error("Team membership could not be checked, so no review was requested") # Passed on as the decision step wrote it. output("decision", value) - line = summary(decision) - print(line, flush=True) - with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as file: - file.write(line + "\n") + # A Push request is not sent yet: the settle job waits for pushes to settle, then writes the final decision's line. + waiting = decision.get("decision") == "fire" and decision.get("kind") == "push" + report_summary(summary(decision, "waiting for pushes to settle" if waiting else "requested")) except Exception as failure: # noqa: BLE001 The decision-failed skip, written first, stands. error(f"Could not report the request decision ({type(failure).__name__})") diff --git a/steps/settle.py b/steps/settle.py new file mode 100644 index 0000000..d4a997d --- /dev/null +++ b/steps/settle.py @@ -0,0 +1,134 @@ +"""The settle job's check: after the settle wait, is a Push request still the last push to a ready pull request? + +Waits SETTLE_MINUTES, then reads the pull request once. Writes the step output decision: the decide job's decision, +passed on as it was written, if the pull request is still open, still not a draft and its head is still the commit +after the push; otherwise a skip with the reason closed, draft or superseded (a newer push), in that order. Anything +but a clear answer is the settle-check-failed skip, with an error annotation saying why. Writes the run summary's line +for the final decision. The step never fails: it writes the settle-check-failed skip first, so that if anything below +breaks, that skip is what the fire job sees. + +Inputs, all environment variables: GITHUB_TOKEN (the job's token, which can only read pull requests), DECISION (the +decide job's decision), SETTLE_MINUTES (the settle wait) and the runner's GITHUB_API_URL, GITHUB_REPOSITORY, +GITHUB_OUTPUT and GITHUB_STEP_SUMMARY. +Python's standard library only (3.10 features); tests/test_settle.py runs this file. +""" + +import json +import os +import re +import time +import urllib.request +from typing import Any + +from helpers import Unreachable, error, github_headers, output, report_summary, send, summary + +FAILED = '{"decision":"skip","reason":"settle-check-failed"}' +SECONDS_PER_MINUTE = 60 +# The longest settle wait, in minutes. The settle job's timeout-minutes leaves room for it and the check. +MAX_MINUTES = 30 +# The most of an answer's body that is read. A pull request is far smaller; a larger answer is not one. +MAX_BODY_BYTES = 1024 * 1024 + +# A whole number of minutes, in ASCII digits. +MINUTES = re.compile(r"[0-9]+") +# A commit id, as the request decision accepts one: exactly 40 lower-case hex characters. +COMMIT = re.compile(r"[0-9a-f]{40}") +# The runner's owner/repository, which goes into the URL: each part starts with a letter, digit or underscore, which +# keeps "." and ".." out. +REPOSITORY = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]*/[A-Za-z0-9_][A-Za-z0-9_.-]*") + + +class CheckFailed(Exception): + """Whether the push was superseded could not be checked; the message says why.""" + + +def skip(reason: str) -> dict[str, Any]: + return {"decision": "skip", "reason": reason} + + +def push_request(value: str) -> tuple[dict[str, Any], int, str]: + """The decide job's decision, its pull request's number and the commit after the push, or CheckFailed.""" + try: + decision = json.loads(value) + except ValueError: + decision = None + if not isinstance(decision, dict) or decision.get("decision") != "fire" or decision.get("kind") != "push": + raise CheckFailed("The decision passed to the settle wait is not a Push request") + pull_request = decision.get("pull_request") + number = pull_request.get("number") if isinstance(pull_request, dict) else None + if isinstance(number, bool) or not isinstance(number, int) or number < 1: + raise CheckFailed("The Push request names no pull request") + head_sha = decision.get("head_sha") + if not isinstance(head_sha, str) or not COMMIT.fullmatch(head_sha): + raise CheckFailed("The Push request names no commit after the push, so a newer push cannot be told from it") + return decision, number, head_sha + + +def wait_seconds(minutes: str) -> float: + if not MINUTES.fullmatch(minutes) or int(minutes) > MAX_MINUTES: + raise CheckFailed(f"The settle-minutes input is not a whole number of minutes from 0 to {MAX_MINUTES}") + return int(minutes) * SECONDS_PER_MINUTE + + +def read_pull_request(token: str, number: int) -> dict[str, Any]: + """The pull request as GitHub's REST API gives it, read once, with no retry and no redirect followed.""" + repository = os.environ.get("GITHUB_REPOSITORY", "") + if not REPOSITORY.fullmatch(repository): + raise CheckFailed("The runner's repository is not a valid owner/repository name") + # The URL starts with the runner's GITHUB_API_URL, which no input can change. + request = urllib.request.Request( # noqa: S310 + f"{os.environ['GITHUB_API_URL']}/repos/{repository}/pulls/{number}", headers=github_headers(token) + ) + try: + # Read with the time limit running: a 200's body is the answer, so one cut off is a failed check. + status, body = send(request, read_ok_bytes=MAX_BODY_BYTES + 1) + except Unreachable as failure: + raise CheckFailed(f"Could not reach GitHub to read the pull request ({failure.kind})") from None + if status != 200: + raise CheckFailed(f"Cannot read pull request #{number}: GitHub answered HTTP {status}") + try: + pull = json.loads(body) if len(body) <= MAX_BODY_BYTES else None + except ValueError: + pull = None + head = pull.get("head") if isinstance(pull, dict) else None + if not ( + isinstance(pull, dict) + and isinstance(pull.get("state"), str) + and isinstance(pull.get("draft"), bool) + and isinstance(head, dict) + and isinstance(head.get("sha"), str) + ): + raise CheckFailed(f"Cannot read pull request #{number}: GitHub's answer was not a pull request") + return pull + + +def settle(token: str, value: str, minutes: str) -> dict[str, Any]: + decision, number, head_sha = push_request(value) + seconds = wait_seconds(minutes) + # An empty token stops here, before the wait, so it never reaches a request. + if not token: + raise CheckFailed("The settle job has no token to read the pull request with") + time.sleep(seconds) + pull = read_pull_request(token, number) + if pull["state"] != "open": + return skip("closed") + if pull["draft"]: + return skip("draft") + if pull["head"]["sha"] != head_sha: + return skip("superseded") + return decision + + +try: + output("decision", FAILED) + value = os.environ.get("DECISION", "") + try: + final = settle(os.environ.get("GITHUB_TOKEN", ""), value, os.environ.get("SETTLE_MINUTES", "")) + except CheckFailed as failure: + error(f"{failure}; no review was requested") + final = json.loads(FAILED) + report_summary(summary(final)) + # A fire is passed on as the decide job wrote it. It is written last, so a failure before it leaves the skip. + output("decision", value if final.get("decision") == "fire" else json.dumps(final, separators=(",", ":"))) +except Exception as failure: # noqa: BLE001 The settle-check-failed skip, written first, stands. + error(f"Could not check whether the push was superseded ({type(failure).__name__}); no review was requested") diff --git a/steps/verify.py b/steps/verify.py index 9a24435..c0ec63b 100644 --- a/steps/verify.py +++ b/steps/verify.py @@ -2,20 +2,27 @@ comment command, that the comment got the review workflow's 👀 reaction, then waits for the stub's reply on the pull request. -Passes only when a comment on the pull request, by the stub routine's account (REPLY_AUTHOR), contains the marker -`integration-test: received` and this run attempt's link (`//actions/runs//attempts/`), which the -review request includes and the stub echoes back. For a comment command, the comment that started the run (COMMENT_ID) -must also have an `eyes` reaction by REACTION_AUTHOR within REACTION_WAIT_SECONDS. Fails with one error annotation that -says what went wrong: no account to expect, the review workflow decided not to request a review (naming the skip -reason), the request was not of the kind the event makes, the request was not sent, the decision is not for the comment -that started the run, no 👀 reaction came in time, or no reply came within WAIT_SECONDS (saying how many comments were -read and how many carried the marker and this attempt's link but came from another author). - -Inputs, all environment variables: DECISION and SENT (the review workflow's outputs), EVENT_NAME and EVENT_ACTION (the -event that started the run), COMMENT_ID (the id of the comment that started a comment command's run), REPLY_AUTHOR (the -login the stub routine posts as), REACTION_AUTHOR (the login the review workflow's react job reacts as), GITHUB_TOKEN -(the job's token, which only reads comments and reactions) and the runner's GITHUB_API_URL, GITHUB_REPOSITORY, -GITHUB_SERVER_URL, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT, GITHUB_OUTPUT and GITHUB_STEP_SUMMARY. +A push that the review workflow's settle wait skipped (superseded by a newer push, or its pull request made a draft or +closed during the wait) passes with a notice and no reply to wait for. The skip passes only when the settle job's own +decision (SETTLE_DECISION) is that skip, so the same skip from the decide job fails, and only when the pull request +(PULL_REQUEST_NUMBER), read once, is in the state the skip names: its head is no longer the commit after the push +(PUSHED_COMMIT), it is a draft, or it is not open. So a settle wait that skips every push fails. + +Otherwise passes only when a comment on the pull request, by the stub routine's account (REPLY_AUTHOR), contains the +marker `integration-test: received` and this run attempt's link (`//actions/runs//attempts/`), +which the review request includes and the stub echoes back. For a comment command, the comment that started the run +(COMMENT_ID) must also have an `eyes` reaction by REACTION_AUTHOR within REACTION_WAIT_SECONDS. Fails with one error +annotation that says what went wrong: no account to expect, the review workflow decided not to request a review +(naming the skip reason), the request was not of the kind the event makes, the request was not sent, the decision is +not for the comment that started the run, no 👀 reaction came in time, or no reply came within WAIT_SECONDS (saying +how many comments were read and how many carried the marker and this attempt's link but came from another author). + +Inputs, all environment variables: DECISION, SETTLE_DECISION and SENT (the review workflow's outputs), EVENT_NAME and +EVENT_ACTION (the event that started the run), PULL_REQUEST_NUMBER and PUSHED_COMMIT (a push's pull request and the +commit after the push), COMMENT_ID (the id of the comment that started a comment command's run), +REPLY_AUTHOR (the login the stub routine posts as), REACTION_AUTHOR (the login the review workflow's react job reacts +as), GITHUB_TOKEN (the job's token, which only reads comments and reactions) and the runner's GITHUB_API_URL, +GITHUB_REPOSITORY, GITHUB_SERVER_URL, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT, GITHUB_OUTPUT and GITHUB_STEP_SUMMARY. Python's standard library only (3.10 features); tests/test_verify.py runs this file. """ @@ -61,12 +68,26 @@ } # HTTP statuses that reading the comments again cannot fix: the token or the pull request is wrong. REFUSED = (401, 403, 404) +# The skips the settle wait makes of a push: a newer push superseded it, or the pull request was made a draft or closed +# during the wait. They are the review workflow working as designed, and pass, but only when the settle job made them: +# the decide job also skips a draft or closed pull request, and for a push the self-test tests, that is a fault. +SETTLED = ("superseded", "draft", "closed") +# What happens next after each settle skip, for the notice. +NOT_REVIEWED = { + "superseded": "a newer push came, whose run is tested unless its own request is skipped too", + "draft": "the pull request was made a draft, and is reviewed again when it is marked ready", + "closed": "the pull request was closed", +} class Failed(Exception): """The self-test failed; the message says why.""" +class NotReviewed(Exception): + """The settle wait skipped the push, by design, so there is no reply to wait for; the message names the reason.""" + + class Unread(Exception): """The comments or reactions could not be read this time; the message says why.""" @@ -117,20 +138,30 @@ def reaction_author() -> str: return login -def requested_pull_request(decision: str, sent: str, name: str, action: str) -> tuple[int, dict[str, Any]]: +def parsed(text: str) -> Any: + """The JSON value of text, or None if it is not JSON.""" + try: + return json.loads(text) + except ValueError: + return None + + +def requested_pull_request( + decision: str, sent: str, name: str, action: str, settle_decision: str +) -> tuple[int, dict[str, Any]]: """The number of the pull request a review was requested for, and the decision, or Failed if none was, or it was - not the kind of request the event makes.""" + not the kind of request the event makes. NotReviewed if the settle job skipped the push by design: the settle + job's own decision, settle_decision, must be the same skip.""" expected = KINDS.get((name, action)) if expected is None: raise Failed(f"The self-test does not test a {name or '(missing)'} event with the action {action!r}") - try: - value: Any = json.loads(decision) - except ValueError: - value = None + value = parsed(decision) if not isinstance(value, dict) or value.get("decision") not in ("fire", "skip"): raise Failed("The review workflow gave no decision to request a review: see its decide job") if value["decision"] == "skip": reason = value.get("reason") + if expected == "push" and reason in SETTLED and parsed(settle_decision) == value: + raise NotReviewed(str(reason)) raise Failed(f"The review workflow decided not to request a review ({reason}): see its decide job") kind = value.get("kind") if kind != expected: @@ -193,6 +224,43 @@ def listing_page(token: str, path: str, what: str, noun: str) -> list[Any]: return items +def settled_state(token: str, reason: str) -> None: + """Failed unless the pull request is in the state the settle skip reason names. Read once: the skip was made after + the same read by the settle job, and a pull request does not leave these states by itself.""" + number = os.environ.get("PULL_REQUEST_NUMBER", "") + pushed = os.environ.get("PUSHED_COMMIT", "") + if not re.fullmatch(r"[1-9][0-9]*", number): + raise Failed("PULL_REQUEST_NUMBER is not a pull request number, so the settle skip cannot be checked") + if not re.fullmatch(r"[0-9a-f]{40}", pushed): + raise Failed("PUSHED_COMMIT is not a commit id, so the settle skip cannot be checked") + what = f"pull request #{number}" + # The URL starts with the runner's GITHUB_API_URL, which no input can change. + request = urllib.request.Request( # noqa: S310 + f"{os.environ['GITHUB_API_URL']}/repos/{os.environ['GITHUB_REPOSITORY']}/pulls/{number}", + headers=github_headers(token), + ) + try: + status, body = send(request, read_ok_bytes=MAX_BODY_BYTES + 1) + except Unreachable as failure: + raise Failed(f"Could not reach GitHub to read {what} ({failure.kind}), to check the settle skip") from None + if status != 200: + raise Failed(f"GitHub answered HTTP {status} when asked for {what}, to check the settle skip") + pull = parsed(body.decode("utf-8", "replace")) if len(body) <= MAX_BODY_BYTES else None + head = pull.get("head") if isinstance(pull, dict) else None + if not isinstance(pull, dict) or not isinstance(head, dict): + raise Failed(f"GitHub's answer for {what} was not a pull request, so the settle skip cannot be checked") + holds = { + "superseded": head.get("sha") != pushed, + "draft": pull.get("draft") is True, + "closed": pull.get("state") != "open", + } + if not holds.get(reason, False): + raise Failed( + f"The settle wait skipped the push as {reason}, but {what} is not in that state " + f"(state {pull.get('state')!r}, draft {pull.get('draft')!r}, head {head.get('sha')!r}): see its settle job" + ) + + def comments_page(token: str, number: int, page: int) -> list[Any]: path = f"repos/{os.environ['GITHUB_REPOSITORY']}/issues/{number}/comments?per_page={PAGE_SIZE}&page={page}" return listing_page(token, path, "the pull request's comments", "comments") @@ -367,17 +435,27 @@ def report(reply: dict[str, Any]) -> None: try: author = reply_author() url = run_url() + token = os.environ.get("GITHUB_TOKEN", "") number, decision = requested_pull_request( os.environ.get("DECISION", ""), os.environ.get("SENT", ""), os.environ.get("EVENT_NAME", ""), os.environ.get("EVENT_ACTION", ""), + os.environ.get("SETTLE_DECISION", ""), ) - token = os.environ.get("GITHUB_TOKEN", "") if decision.get("kind") == "comment-command": comment = triggering_comment(decision) report_reaction(wait_for_reaction(token, comment, reaction_author()), comment) report(wait_for_reply(token, number, url, author)) +except NotReviewed as skipped: + try: + settled_state(os.environ.get("GITHUB_TOKEN", ""), str(skipped)) + except Failed as failure: + error(str(failure)) + sys.exit(1) + text = f"The settle wait skipped the push ({skipped}), so it was not reviewed: {NOT_REVIEWED[str(skipped)]}" + print(f"::notice title=Push not reviewed::{escaped(text)}", flush=True) + write_summary(f"Self-test: passed. The push was not reviewed ({skipped}): the settle wait skipped it, by design.\n") except Failed as failure: error(str(failure)) sys.exit(1) diff --git a/tests/harness.py b/tests/harness.py index ebf7c7d..0423522 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -19,8 +19,10 @@ import email.message import functools import http.server +import json import os import pathlib +import re import shutil import socket import subprocess @@ -426,3 +428,165 @@ def __exit__(self, *exc): def paths(self): return [path for _, path, _ in self.requests] + + +class Expression: + """Evaluates a job's `if:` condition, or another expression, as GitHub does, for the little of GitHub's expression + language the workflows use: context paths such as `github.` and `needs.`, string literals, true, false, ==, !=, !, + && and || with parentheses, the functions startsWith, fromJSON and format, and the status function cancelled(), + which is true when the context's "cancelled" is. As in GitHub, a missing property is null, && and || give one of + their operands, == compares strings ignoring case, as startsWith does, and fromJSON of text that is not JSON is an + error. Both sides of && and || are always evaluated, so an expression that needs GitHub to stop early to avoid an + error fails here.""" + + TOKEN = re.compile( + r"\s*(?:(&&|\|\||==|!=|!|\(|\)|,)|'((?:[^']|'')*)'|([A-Za-z_][A-Za-z0-9_.-]*)(?=\s*(\())?" + r"|\.([A-Za-z_][A-Za-z0-9_.-]*))" + ) + + def __init__(self, text, context): + self.cancelled = bool(context.get("cancelled")) + text = text.strip() + if text.startswith("${{") and text.endswith("}}"): + text = text[3:-2] + self.tokens = [] + position = 0 + while text[position:].strip(): + match = self.TOKEN.match(text, position) + if match is None: + raise ValueError(f"cannot read the expression at {text[position:]!r}") + operator, literal, name, call, member = match.groups() + if member: + # A property of what comes before it, such as fromJSON(...).decision. + self.tokens.append(("member", member)) + elif operator: + self.tokens.append(("op", operator)) + elif literal is not None: + self.tokens.append(("value", literal.replace("''", "'"))) + elif call: + self.tokens.append(("function", name)) + else: + self.tokens.append(("value", self.lookup(name, context))) + position = match.end() + self.position = 0 + + @staticmethod + def lookup(name, context): + if name in ("true", "false", "null"): + return {"true": True, "false": False, "null": None}[name] + found = context + for part in name.split("."): + found = found.get(part) if isinstance(found, dict) else None + return found + + def peek(self): + return self.tokens[self.position] if self.position < len(self.tokens) else (None, None) + + def take(self, operator): + if self.peek() == ("op", operator): + self.position += 1 + return True + return False + + def evaluate(self): + return bool(self.result()) + + def result(self): + result = self.either() + if self.position != len(self.tokens): + raise ValueError("the expression has text left over") + return result + + def render(self): + """The value as GitHub writes it into an `env:` entry: true and false in lower case, null as empty.""" + result = self.result() + if isinstance(result, bool): + return "true" if result else "false" + return "" if result is None else str(result) + + def either(self): + left = self.both() + while self.take("||"): + right = self.both() + left = left or right + return left + + def both(self): + left = self.comparison() + while self.take("&&"): + right = self.comparison() + left = left and right + return left + + def comparison(self): + left = self.unary() + for operator in ("==", "!="): + if self.take(operator): + right = self.unary() + same = self.same(left, right) + return same if operator == "==" else not same + return left + + @staticmethod + def same(left, right): + if isinstance(left, str) and isinstance(right, str): + return left.lower() == right.lower() + return type(left) is type(right) and left == right + + @staticmethod + def text(value): + """A value as GitHub casts it to a string: null is empty, true and false are lower case.""" + if value is None: + return "" + if isinstance(value, bool): + return "true" if value else "false" + return str(value) + + @classmethod + def call(cls, name, arguments): + if name == "startsWith": + whole, start = arguments + return cls.text(whole).lower().startswith(cls.text(start).lower()) + if name == "fromJSON": + return json.loads(arguments[0]) + if name == "format": + template, *values = arguments + for number, item in enumerate(values): + template = template.replace(f"{{{number}}}", cls.text(item)) + return template + raise ValueError(f"the function {name!r} is not known") + + def unary(self): + if self.take("!"): + return not self.unary() + result = self.primary() + while self.peek()[0] == "member": + result = self.lookup(self.peek()[1], result) + self.position += 1 + return result + + def primary(self): + if self.take("("): + result = self.either() + if not self.take(")"): + raise ValueError("a parenthesis is not closed") + return result + kind, token = self.peek() + if kind == "function": + self.position += 1 + if not self.take("("): + raise ValueError(f"the function {token!r} has no arguments") + if token == "cancelled": + if not self.take(")"): + raise ValueError("cancelled() takes no arguments") + return self.cancelled + arguments = [self.either()] + while self.take(","): + arguments.append(self.either()) + if not self.take(")"): + raise ValueError(f"the call to {token!r} is not closed") + return self.call(token, arguments) + if kind != "value": + raise ValueError(f"expected a value, found {token!r}") + self.position += 1 + return token diff --git a/tests/test_decision_file.py b/tests/test_decision_file.py index 187c0b8..0049547 100644 --- a/tests/test_decision_file.py +++ b/tests/test_decision_file.py @@ -97,8 +97,8 @@ class CheckoutStepsTest(unittest.TestCase): def jobs(self): return sorted({job for job, _ in file_steps()}) - def test_the_decide_fire_and_react_jobs_check_out_this_repository(self): - self.assertEqual(self.jobs(), ["decide", "fire", "react"]) + def test_the_decide_settle_fire_and_react_jobs_check_out_this_repository(self): + self.assertEqual(self.jobs(), ["decide", "fire", "react", "settle"]) def test_each_checkout_is_the_same_apart_from_its_name_and_sparse_patterns(self): # Compared value by value, because each yq prints a whole step differently (one keeps its comments). @@ -134,7 +134,8 @@ def test_the_fire_jobs_sent_output_is_the_send_steps_alone(self): self.assertEqual(_yq(".jobs.fire.outputs.sent").strip(), "${{ steps.send.outputs.sent }}") def test_the_react_job_runs_only_when_the_request_was_sent(self): - self.assertTrue(_yq(".jobs.react.if").strip().startswith("needs.fire.outputs.sent == 'true'")) + condition = _yq(".jobs.react.if").strip() + self.assertIn(" && needs.fire.result == 'success' && needs.fire.outputs.sent == 'true' && ", condition) if __name__ == "__main__": diff --git a/tests/test_permissions.py b/tests/test_permissions.py index c004c7b..1cf08a8 100644 --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -12,6 +12,8 @@ # Adding a reaction to a pull request's conversation comment needs pull-requests: write. With issues: write alone, # GitHub answered HTTP 403 on the first live comment command (run 44665882864). REACT_PERMISSIONS = ["issues=write", "pull-requests=write"] +# The settle job reads the pull request after the settle wait, and nothing else. +SETTLE_PERMISSIONS = ["pull-requests=read"] def permissions(path: str, workflow: pathlib.Path) -> list[str]: @@ -23,14 +25,21 @@ class PermissionsTest(unittest.TestCase): def test_the_react_job_can_react_to_a_pull_request_comment(self) -> None: self.assertEqual(permissions(".jobs.react", WORKFLOW), REACT_PERMISSIONS) + def test_the_settle_job_can_only_read_pull_requests(self) -> None: + self.assertEqual(permissions(".jobs.settle", WORKFLOW), SETTLE_PERMISSIONS) + def test_the_other_jobs_hold_no_permissions(self) -> None: jobs = _yq(".jobs | keys | .[]").split() for job in jobs: - if job == "react": + if job in ("react", "settle"): continue with self.subTest(job=job): self.assertEqual(_yq(f".jobs.{job}.permissions | length").strip(), "0") + def test_what_the_react_job_holds_covers_what_the_settle_job_holds(self) -> None: + # So a caller needs no new permission for the settle job: write includes read. + self.assertIn("pull-requests=write", REACT_PERMISSIONS) + def test_the_example_caller_grants_what_the_react_job_holds(self) -> None: self.assertEqual(permissions(".jobs.review", EXAMPLE), REACT_PERMISSIONS) self.assertEqual(_yq(".permissions | length", EXAMPLE).strip(), "0") diff --git a/tests/test_python_steps.py b/tests/test_python_steps.py index b77d3f6..1bf173c 100644 --- a/tests/test_python_steps.py +++ b/tests/test_python_steps.py @@ -15,10 +15,10 @@ def test_no_step_runs_python_inline(self): self.assertNotEqual(shells, []) self.assertEqual([shell for shell in shells if "python" in shell], []) - def test_the_lookup_the_report_the_routine_call_and_the_reaction_run_from_files(self): + def test_the_lookup_the_report_the_settle_check_the_routine_call_and_the_reaction_run_from_files(self): self.assertEqual( set(file_steps()), - {("decide", "lookup"), ("decide", "final"), ("fire", "send"), ("react", "reaction")}, + {("decide", "lookup"), ("decide", "final"), ("settle", "check"), ("fire", "send"), ("react", "reaction")}, ) def test_each_step_file_step_has_an_id_so_it_is_listed_and_checked(self): diff --git a/tests/test_report.py b/tests/test_report.py index 4fe8020..6558d42 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -42,6 +42,15 @@ def test_a_fire_decision_is_passed_on(self): self.assertEqual(result.errors(), []) self.assertEqual(result.summary, "Claude review: requested (ready, by @alice, pull request #7)\n") + def test_a_push_fire_is_passed_on_as_waiting_for_pushes_to_settle(self): + # The settle job writes the final decision's line, so this one must not say the review was requested. + push = {**FIRE, "kind": "push", "react": False, "head_sha": "2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e"} + result = self.report(first=compact(push)) + self.assertEqual(self.decision(result), push) + self.assertEqual( + result.summary, "Claude review: waiting for pushes to settle (push, by @alice, pull request #7)\n" + ) + def test_a_skip_decision_is_passed_on(self): result = self.report(first=compact({"decision": "skip", "reason": "draft"})) self.assertEqual(self.decision(result), {"decision": "skip", "reason": "draft"}) diff --git a/tests/test_self_test.py b/tests/test_self_test.py index 6b755bc..df99619 100644 --- a/tests/test_self_test.py +++ b/tests/test_self_test.py @@ -7,7 +7,7 @@ import tempfile import unittest -from harness import ROOT, SELF_TEST, _yq, file_steps, step_field, step_file_path, step_shells +from harness import ROOT, SELF_TEST, Expression, _yq, file_steps, step_field, step_file_path, step_shells REPOSITORY = "cipherstash/workflows" DECISION_FILE = ROOT / "request-decision" / "decision.jq" @@ -17,147 +17,6 @@ def value(query): return _yq(query, SELF_TEST).strip() -class Expression: - """Evaluates a job's `if:` condition as GitHub does, for the little of GitHub's expression language the self-test - uses: `github.` context paths, string literals, true, false, ==, !=, !, && and || with parentheses, and the - functions startsWith, fromJSON and format. As in GitHub, a missing property is null, && and || give one - of their operands, and == compares strings ignoring case, as startsWith does.""" - - TOKEN = re.compile(r"\s*(?:(&&|\|\||==|!=|!|\(|\)|,)|'((?:[^']|'')*)'|([A-Za-z_][A-Za-z0-9_.-]*)(?=\s*(\())?)") - - def __init__(self, text, context): - text = text.strip() - if text.startswith("${{") and text.endswith("}}"): - text = text[3:-2] - self.tokens = [] - position = 0 - while text[position:].strip(): - match = self.TOKEN.match(text, position) - if match is None: - raise ValueError(f"cannot read the expression at {text[position:]!r}") - operator, literal, name, call = match.groups() - if operator: - self.tokens.append(("op", operator)) - elif literal is not None: - self.tokens.append(("value", literal.replace("''", "'"))) - elif call: - self.tokens.append(("function", name)) - else: - self.tokens.append(("value", self.lookup(name, context))) - position = match.end() - self.position = 0 - - @staticmethod - def lookup(name, context): - if name in ("true", "false", "null"): - return {"true": True, "false": False, "null": None}[name] - found = context - for part in name.split("."): - found = found.get(part) if isinstance(found, dict) else None - return found - - def peek(self): - return self.tokens[self.position] if self.position < len(self.tokens) else (None, None) - - def take(self, operator): - if self.peek() == ("op", operator): - self.position += 1 - return True - return False - - def evaluate(self): - return bool(self.result()) - - def result(self): - result = self.either() - if self.position != len(self.tokens): - raise ValueError("the expression has text left over") - return result - - def render(self): - """The value as GitHub writes it into an `env:` entry: true and false in lower case, null as empty.""" - result = self.result() - if isinstance(result, bool): - return "true" if result else "false" - return "" if result is None else str(result) - - def either(self): - left = self.both() - while self.take("||"): - right = self.both() - left = left or right - return left - - def both(self): - left = self.comparison() - while self.take("&&"): - right = self.comparison() - left = left and right - return left - - def comparison(self): - left = self.unary() - for operator in ("==", "!="): - if self.take(operator): - right = self.unary() - same = self.same(left, right) - return same if operator == "==" else not same - return left - - @staticmethod - def same(left, right): - if isinstance(left, str) and isinstance(right, str): - return left.lower() == right.lower() - return type(left) is type(right) and left == right - - @staticmethod - def text(value): - """A value as GitHub casts it to a string: null is empty, true and false are lower case.""" - if value is None: - return "" - if isinstance(value, bool): - return "true" if value else "false" - return str(value) - - @classmethod - def call(cls, name, arguments): - if name == "startsWith": - whole, start = arguments - return cls.text(whole).lower().startswith(cls.text(start).lower()) - if name == "fromJSON": - return json.loads(arguments[0]) - if name == "format": - template, *values = arguments - for number, item in enumerate(values): - template = template.replace(f"{{{number}}}", cls.text(item)) - return template - raise ValueError(f"the function {name!r} is not known") - - def unary(self): - if self.take("!"): - return not self.unary() - if self.take("("): - result = self.either() - if not self.take(")"): - raise ValueError("a parenthesis is not closed") - return result - kind, token = self.peek() - if kind == "function": - self.position += 1 - if not self.take("("): - raise ValueError(f"the function {token!r} has no arguments") - arguments = [self.either()] - while self.take(","): - arguments.append(self.either()) - if not self.take(")"): - raise ValueError(f"the call to {token!r} is not closed") - return self.call(token, arguments) - if kind != "value": - raise ValueError(f"expected a value, found {token!r}") - self.position += 1 - return token - - def event( action="opened", draft=False, @@ -325,6 +184,10 @@ def test_it_uses_the_stub_routines_trigger_and_token(self): value(".jobs.review.secrets.CLAUDE_ROUTINE_TOKEN"), "${{ secrets.CLAUDE_ROUTINE_INTEGRATION_TEST_TOKEN }}" ) + def test_it_passes_a_short_settle_wait(self): + # A minute, so a run for a push stays quick, and two pushes within it still test the superseded skip. + self.assertEqual(value('.jobs.review.with."settle-minutes"'), "1") + def test_it_never_names_the_real_routines_trigger_or_token(self): text = SELF_TEST.read_text(encoding="utf-8") self.assertIsNone(re.search(r"secrets\.CLAUDE_ROUTINE_TOKEN\b", text)) @@ -520,7 +383,7 @@ def test_the_verify_job_waits_for_the_review_job_and_only_reads(self): self.assertEqual(value(".jobs.verify.if"), "${{ !cancelled() && needs.review.result != 'skipped' }}") self.assertEqual( value('.jobs.verify.permissions | to_entries | map(.key + "=" + .value) | .[]').split(), - ["issues=read"], + ["issues=read", "pull-requests=read"], ) def test_the_verify_job_is_told_which_event_started_the_run(self): @@ -544,6 +407,11 @@ def test_the_verify_job_reads_the_review_workflows_outputs(self): self.assertEqual( value(".jobs.verify.steps[] | select(.id == \"verify\") | .env.SENT"), "${{ needs.review.outputs.sent }}" ) + # The settle job's own decision, so a push's draft or closed skip passes only when the settle wait made it. + self.assertEqual( + value(".jobs.verify.steps[] | select(.id == \"verify\") | .env.SETTLE_DECISION"), + "${{ needs.review.outputs.settle-decision }}", + ) def test_the_verify_step_accepts_a_reply_only_from_the_stub_routines_account(self): self.assertEqual( @@ -556,8 +424,19 @@ def test_the_verify_job_does_not_filter_the_reply_by_author_association(self): def test_the_review_workflow_gives_its_decision_and_whether_it_sent_the_request(self): outputs = '.on.workflow_call.outputs' - self.assertEqual(_yq(f"{outputs}.decision.value").strip(), "${{ jobs.decide.outputs.decision }}") + # The final decision: the settle job's for a Push request, which is skipped for every other kind. A settle job + # that ran but left no output, such as one whose runner was lost, gives the settle-check-failed skip, never the + # decide job's fire. + self.assertEqual( + _yq(f"{outputs}.decision.value").strip(), + "${{ fromJSON(jobs.decide.outputs.decision || '{}').decision == 'fire'" + " && fromJSON(jobs.decide.outputs.decision || '{}').kind == 'push'" + " && (jobs.settle.outputs.decision || '{\"decision\":\"skip\",\"reason\":\"settle-check-failed\"}')" + " || jobs.decide.outputs.decision }}", + ) self.assertEqual(_yq(f"{outputs}.sent.value").strip(), "${{ jobs.fire.outputs.sent }}") + # The settle job's decision alone, empty when it did not run, so a caller can tell which job made a skip. + self.assertEqual(_yq(f'{outputs}."settle-decision".value').strip(), "${{ jobs.settle.outputs.decision }}") def test_the_only_step_file_is_the_verify_step_and_it_is_checked_out(self): self.assertEqual(set(file_steps(SELF_TEST)), {("verify", "verify")}) diff --git a/tests/test_settle.py b/tests/test_settle.py new file mode 100644 index 0000000..1f7eb13 --- /dev/null +++ b/tests/test_settle.py @@ -0,0 +1,282 @@ +"""The settle job's check: after the settle wait, is a Push request still the last push to a ready pull request?""" + +import json +import re +import time +import unittest +from typing import ClassVar + +from harness import ( + StubServer, + _yq, + closed_port_url, + run_step, + run_step_as_written, + step_file_copy, + step_file_path, + step_script, +) + +TOKEN = "ghs_unitTestSettleTokenThatMustNeverBePrinted01" +HEAD = "2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e" +NEWER = "3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f" +PULL_PATH = "/repos/cipherstash/example/pulls/42" +PUSH = { + "decision": "fire", + "kind": "push", + "requester": "octocat", + "pull_request": {"number": 42, "url": "https://github.com/cipherstash/example/pull/42"}, + "react": False, + "head_sha": HEAD, + "text": "Review pull request #42 in cipherstash/example: https://github.com/cipherstash/example/pull/42\n\n" + "Kind of review request: push.", +} + + +def compact(value): + return json.dumps(value, separators=(",", ":")) + + +def pull_request(state="open", draft=False, head=HEAD): + return (200, json.dumps({"number": 42, "state": state, "draft": draft, "head": {"sha": head}})) + + +def inputs(**overrides): + env = {"GITHUB_TOKEN": TOKEN, "DECISION": compact(PUSH), "SETTLE_MINUTES": "0"} + env.update(overrides) + return env + + +class SettleTest(unittest.TestCase): + def settle(self, routes=None, api_url=None, substitutions=None, **overrides): + with StubServer(routes) as stub: + result = run_step( + "settle", "check", inputs(**overrides), api_url=api_url or stub.url, substitutions=substitutions + ) + self.stub = stub + # The settle job never fails: every outcome is a decision. + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn(TOKEN, result.everything(), "the job's token was printed or written to an output") + return result + + def decision(self, result): + return json.loads(result.outputs["decision"]) + + def assert_failed(self, result, message): + self.assertEqual(self.decision(result), {"decision": "skip", "reason": "settle-check-failed"}) + self.assertEqual(len(result.errors()), 1, result.stdout) + self.assertIn(message, result.errors()[0]) + self.assertIn("no review was requested", result.errors()[0]) + self.assertEqual(result.summary, "Claude review: skipped (settle-check-failed)\n") + + +class GivenThePullRequestIsUnchanged(SettleTest): + def test_the_push_request_is_passed_on(self): + result = self.settle({PULL_PATH: pull_request()}) + self.assertEqual(self.decision(result), PUSH) + self.assertEqual(result.errors(), []) + self.assertEqual(result.summary, "Claude review: requested (push, by @octocat, pull request #42)\n") + + def test_the_pull_request_is_read_once_with_the_jobs_token(self): + self.settle({PULL_PATH: pull_request()}) + self.assertEqual(self.stub.paths(), [PULL_PATH]) + _, _, headers = self.stub.requests[0] + self.assertEqual(headers.get("Authorization"), f"Bearer {TOKEN}") + self.assertEqual(headers.get("Accept"), "application/vnd.github+json") + self.assertEqual(headers.get("X-GitHub-Api-Version"), "2022-11-28") + + +class GivenThePullRequestChangedDuringTheWait(SettleTest): + def assert_skipped(self, result, reason): + self.assertEqual(self.decision(result), {"decision": "skip", "reason": reason}) + # A skip after the wait is an expected outcome, not an error: the run stays green and quiet. + self.assertEqual(result.errors(), []) + self.assertEqual(result.summary, f"Claude review: skipped ({reason})\n") + + def test_a_newer_push_skips_as_superseded(self): + self.assert_skipped(self.settle({PULL_PATH: pull_request(head=NEWER)}), "superseded") + + def test_a_pull_request_made_a_draft_skips_as_draft(self): + self.assert_skipped(self.settle({PULL_PATH: pull_request(draft=True)}), "draft") + + def test_a_closed_pull_request_skips_as_closed(self): + self.assert_skipped(self.settle({PULL_PATH: pull_request(state="closed")}), "closed") + + def test_closed_is_named_before_draft_and_draft_before_superseded(self): + self.assert_skipped(self.settle({PULL_PATH: pull_request(state="closed", draft=True, head=NEWER)}), "closed") + self.assert_skipped(self.settle({PULL_PATH: pull_request(draft=True, head=NEWER)}), "draft") + + +class GivenNoClearAnswerFromGitHub(SettleTest): + def test_an_error_status_fails_the_check(self): + for status in (401, 403, 404, 422, 500, 502): + with self.subTest(status=status): + result = self.settle({PULL_PATH: (status, json.dumps({"message": "nope"}))}) + self.assert_failed(result, f"GitHub answered HTTP {status}") + + def test_a_redirect_is_not_followed_and_fails_the_check(self): + for status in (301, 302, 307, 308): + with self.subTest(status=status): + # The redirect points at a second server that would answer an unchanged pull request. + with StubServer({"/elsewhere": pull_request()}) as elsewhere: + result = self.settle({PULL_PATH: (status, "", {"Location": f"{elsewhere.url}/elsewhere"})}) + self.assert_failed(result, f"GitHub answered HTTP {status}") + self.assertEqual(elsewhere.requests, [], "the redirect was followed") + + def test_a_body_that_is_not_json_fails_the_check(self): + self.assert_failed(self.settle({PULL_PATH: (200, "not json")}), "was not a pull request") + + def test_a_body_that_is_not_a_pull_request_fails_the_check(self): + bodies: list[object] = [ + [], + "open", + {}, + {"state": "open", "draft": False}, + {"state": "open", "draft": False, "head": HEAD}, + {"state": "open", "draft": False, "head": {}}, + {"state": "open", "draft": False, "head": {"sha": 7}}, + {"state": "open", "draft": "false", "head": {"sha": HEAD}}, + {"state": None, "draft": False, "head": {"sha": HEAD}}, + {"draft": False, "head": {"sha": HEAD}}, + ] + for body in bodies: + with self.subTest(body=body): + self.assert_failed(self.settle({PULL_PATH: (200, json.dumps(body))}), "was not a pull request") + + def test_an_answer_larger_than_a_pull_request_fails_the_check(self): + body = json.dumps({"state": "open", "draft": False, "head": {"sha": HEAD}, "padding": "x" * 1_100_000}) + self.assert_failed(self.settle({PULL_PATH: (200, body)}), "was not a pull request") + + def test_an_answer_that_never_ends_is_cut_off_after_the_total_time(self): + started = time.monotonic() + result = self.settle({PULL_PATH: StubServer.DRIP}, substitutions={"TOTAL_SECONDS = 30": "TOTAL_SECONDS = 0.5"}) + self.assert_failed(result, "Could not reach GitHub to read the pull request (TotalTimeout)") + self.assertLess(time.monotonic() - started, 5, "the check ran on past its total time") + + def test_no_answer_in_time_fails_the_check(self): + result = self.settle( + {PULL_PATH: StubServer.HANG}, substitutions={"TIMEOUT_SECONDS = 10": "TIMEOUT_SECONDS = 0.5"} + ) + self.assert_failed(result, "Could not reach GitHub to read the pull request") + + def test_a_connection_closed_without_an_answer_fails_the_check(self): + self.assert_failed(self.settle({PULL_PATH: StubServer.DROP}), "Could not reach GitHub to read the pull request") + + def test_a_refused_connection_fails_the_check(self): + self.assert_failed(self.settle(api_url=closed_port_url()), "Could not reach GitHub to read the pull request") + + def test_an_empty_or_missing_token_fails_the_check_without_asking_github(self): + for token in ("", None): + with self.subTest(token=token): + self.assert_failed(self.settle(GITHUB_TOKEN=token), "no token") + self.assertEqual(self.stub.paths(), []) + + +class GivenTheSettleWait(SettleTest): + # A minute lasts a tenth of a second in these tests. + FAST: ClassVar[dict[str, str]] = {"SECONDS_PER_MINUTE = 60": "SECONDS_PER_MINUTE = 0.1"} + + def test_a_wait_of_zero_checks_at_once(self): + started = time.monotonic() + result = self.settle({PULL_PATH: pull_request()}, SETTLE_MINUTES="0") + self.assertEqual(self.decision(result), PUSH) + self.assertLess(time.monotonic() - started, 3) + + def test_the_check_comes_after_the_wait(self): + started = time.monotonic() + result = self.settle({PULL_PATH: pull_request()}, substitutions=self.FAST, SETTLE_MINUTES="5") + self.assertEqual(self.decision(result), PUSH) + self.assertGreaterEqual(time.monotonic() - started, 0.5) + + def test_the_longest_wait_is_thirty_minutes(self): + result = self.settle({PULL_PATH: pull_request()}, substitutions=self.FAST, SETTLE_MINUTES="30") + self.assertEqual(self.decision(result), PUSH) + + def test_a_wait_that_is_not_a_whole_number_of_minutes_up_to_thirty_fails_without_asking_github(self): + for minutes in ("", "-1", "31", "2.5", "five", "1e3", " 5", "\uff15", None): + with self.subTest(minutes=minutes): + result = self.settle({PULL_PATH: pull_request()}, substitutions=self.FAST, SETTLE_MINUTES=minutes) + self.assert_failed(result, "settle-minutes") + self.assertEqual(self.stub.paths(), []) + + +class GivenADecisionThatCannotBeChecked(SettleTest): + def test_a_decision_without_a_commit_after_the_push_fails_without_asking_github(self): + for head_sha in (None, "", "abc", HEAD.upper(), HEAD + "0", 7): + with self.subTest(head_sha=head_sha): + result = self.settle(DECISION=compact({**PUSH, "head_sha": head_sha})) + self.assert_failed(result, "names no commit after the push") + self.assertEqual(self.stub.paths(), []) + + def test_a_decision_without_a_pull_request_number_fails_without_asking_github(self): + for pull in (None, {}, {"number": "42"}, {"number": 0}, {"number": True}, {"number": "42/../../x"}): + with self.subTest(pull_request=pull): + result = self.settle(DECISION=compact({**PUSH, "pull_request": pull})) + self.assert_failed(result, "names no pull request") + self.assertEqual(self.stub.paths(), []) + + def test_a_decision_that_is_not_a_push_fire_fails_without_asking_github(self): + for value in ("", "not json", "[]", compact({**PUSH, "kind": "ready"}), compact({"decision": "skip"})): + with self.subTest(value=value): + self.assert_failed(self.settle(DECISION=value), "is not a Push request") + self.assertEqual(self.stub.paths(), []) + + def test_a_repository_name_that_is_not_valid_fails_without_asking_github(self): + for repository in ("", "cipherstash", "cipherstash/example/x", "../example", "cipher stash/example"): + with self.subTest(repository=repository): + with StubServer({PULL_PATH: pull_request()}) as stub: + result = run_step( + "settle", "check", inputs(), api_url=stub.url, runner={"GITHUB_REPOSITORY": repository} + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assert_failed(result, "repository") + self.assertEqual(stub.paths(), []) + + +class GivenTheStepAsTheWorkflowWritesIt(unittest.TestCase): + """The step as the workflow writes it, run by bash: it runs the checked-out file, or, without it, still leaves the + settle-check-failed skip, an error and the summary line, as the file does when it cannot check.""" + + def run_as_written(self, step_file, outcome="success"): + with StubServer({PULL_PATH: pull_request()}) as stub: + env = inputs(STEP_FILE=str(step_file), CHECKOUT_OUTCOME=outcome) + result = run_step_as_written("settle", "check", env, api_url=stub.url) + self.assertEqual(result.returncode, 0, result.stderr) + return result + + def assert_failed(self, result): + self.assertEqual(json.loads(result.outputs["decision"]), {"decision": "skip", "reason": "settle-check-failed"}) + self.assertIn("no review was requested", result.errors()[-1]) + self.assertTrue(result.summary.endswith("Claude review: skipped (settle-check-failed)\n"), result.summary) + + def test_with_the_file_the_step_runs_it(self): + result = self.run_as_written(step_file_path("settle", "check")) + self.assertEqual(json.loads(result.outputs["decision"]), PUSH) + self.assertEqual(result.errors(), []) + self.assertEqual(result.summary, "Claude review: requested (push, by @octocat, pull request #42)\n") + + def test_without_the_file_the_step_writes_the_settle_check_failed_skip(self): + self.assert_failed(self.run_as_written("/nonexistent/steps/settle.py")) + + def test_a_failed_checkout_writes_the_settle_check_failed_skip(self): + self.assert_failed(self.run_as_written(step_file_path("settle", "check"), outcome="failure")) + + def test_missing_or_broken_helpers_leave_the_settle_check_failed_skip(self): + for helpers_source in (None, "def broken(:\n"): + with self.subTest(helpers=helpers_source), step_file_copy("settle", "check", helpers_source) as step_file: + self.assert_failed(self.run_as_written(step_file)) + + +class GivenTheSettleCheckFailedSkipIsWrittenInSeveralPlaces(unittest.TestCase): + def test_the_job_output_fallback_the_wrapper_and_the_step_file_agree(self): + failed = re.search(r"^FAILED = '(.*)'$", step_file_path("settle", "check").read_text(encoding="utf-8"), re.M) + if failed is None: + self.fail("steps/settle.py has no FAILED line") + self.assertEqual(failed.group(1), compact({"decision": "skip", "reason": "settle-check-failed"})) + self.assertIn(f"|| '{failed.group(1)}' }}}}", _yq(".jobs.settle.outputs.decision")) + script, _ = step_script("settle", "check") + self.assertIn(f"echo 'decision={failed.group(1)}' >>\"$GITHUB_OUTPUT\"", script) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_settle_job.py b/tests/test_settle_job.py new file mode 100644 index 0000000..70e3bdf --- /dev/null +++ b/tests/test_settle_job.py @@ -0,0 +1,179 @@ +"""The settle job's place in the review workflow: when it runs, what it holds, and how the fire and react jobs and the +workflow's decision output use its result.""" + +import json +import re +import unittest + +from harness import STEPS_DIR, Expression, _yq, step_field + +PUSH = { + "decision": "fire", + "kind": "push", + "requester": "octocat", + "pull_request": {"number": 42, "url": "https://github.com/cipherstash/example/pull/42"}, + "react": False, + "head_sha": "2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e", + "text": "Review pull request #42 in cipherstash/example.", +} +COMMENT = {**PUSH, "kind": "comment-command", "react": True, "comment_id": 7} +for kind_only in ("head_sha",): + del COMMENT[kind_only] +READY = {**PUSH, "kind": "ready"} +del READY["head_sha"] +REQUESTED = {**READY, "kind": "requested-reviewer"} +SKIP = {"decision": "skip", "reason": "draft"} +SUPERSEDED = {"decision": "skip", "reason": "superseded"} +SETTLE_FAILED = {"decision": "skip", "reason": "settle-check-failed"} + + +def compact(value): + return json.dumps(value, separators=(",", ":")) + + +def needs(decision, settle_result="skipped", settle_decision=None, decide_result="success", **more): + """The needs context of a job after decide and settle, as GitHub gives it: a skipped job has empty outputs.""" + context = { + "decide": {"result": decide_result, "outputs": {"decision": compact(decision)}}, + "settle": { + "result": settle_result, + "outputs": {} if settle_decision is None else {"decision": compact(settle_decision)}, + }, + } + context.update(more) + return context + + +def runs(job, context, cancelled=False): + return Expression(_yq(f".jobs.{job}.if").strip(), {"needs": context, "cancelled": cancelled}).evaluate() + + +class SettleJobTest(unittest.TestCase): + def test_it_runs_after_the_decide_job_only_for_a_push_fire(self): + self.assertEqual(_yq(".jobs.settle.needs").strip(), "decide") + self.assertTrue(runs("settle", needs(PUSH))) + for decision in (READY, COMMENT, REQUESTED, SKIP, {"decision": "skip", "reason": "draft", "kind": "push"}): + with self.subTest(decision=decision): + self.assertFalse(runs("settle", needs(decision))) + + def test_it_holds_only_pull_requests_read(self): + entries = _yq('.jobs.settle.permissions | to_entries | map(.key + "=" + .value) | .[]').split() + self.assertEqual(entries, ["pull-requests=read"]) + + def test_it_holds_no_secrets(self): + job = _yq(".jobs.settle | tojson") + self.assertNotIn("secrets.", job) + self.assertNotIn("secrets[", job) + # Its only token is the job's own, which the permissions above limit. + self.assertEqual(step_field("settle", "check", ".env.GITHUB_TOKEN"), "${{ github.token }}") + + def test_it_has_no_concurrency_group_so_nothing_is_cancelled_or_kept_waiting(self): + self.assertEqual(_yq(".jobs.settle.concurrency").strip(), "null") + # The fire job's queue is unchanged: it waits, and never cancels. + self.assertEqual(_yq('.jobs.fire.concurrency."cancel-in-progress"').strip(), "false") + + def test_its_step_gets_the_decide_jobs_decision_and_the_settle_wait(self): + self.assertEqual(step_field("settle", "check", ".env.DECISION"), "${{ needs.decide.outputs.decision }}") + self.assertEqual(step_field("settle", "check", ".env.SETTLE_MINUTES"), "${{ inputs.settle-minutes }}") + self.assertEqual(step_field("settle", "check", '."continue-on-error"'), "true") + + def test_the_settle_wait_is_an_input_of_five_minutes_by_default(self): + self.assertEqual(_yq('.on.workflow_call.inputs."settle-minutes".type').strip(), "number") + self.assertEqual(_yq('.on.workflow_call.inputs."settle-minutes".default').strip(), "5") + + def test_its_timeout_leaves_room_for_the_longest_wait(self): + found = re.search(r"^MAX_MINUTES = ([0-9]+)$", (STEPS_DIR / "settle.py").read_text(encoding="utf-8"), re.M) + if found is None: + self.fail("steps/settle.py has no MAX_MINUTES line") + # The wait, then at most two of the shared helper's 30-second requests' worth, and the checkout. + self.assertGreaterEqual(int(_yq('.jobs.settle."timeout-minutes"').strip()), int(found.group(1)) + 5) + + +class FireJobTest(unittest.TestCase): + def test_it_waits_for_the_settle_job(self): + self.assertEqual(_yq(".jobs.fire.needs[]").split(), ["decide", "settle"]) + + def test_every_other_kind_fires_on_the_decision_alone(self): + for decision in (READY, COMMENT, REQUESTED): + with self.subTest(kind=decision["kind"]): + self.assertTrue(runs("fire", needs(decision))) + + def test_a_push_fires_only_when_the_settle_job_passes_it_on(self): + self.assertTrue(runs("fire", needs(PUSH, "success", PUSH))) + for result, decision in ( + ("success", SUPERSEDED), + ("success", SETTLE_FAILED), + ("success", {"decision": "skip", "reason": "draft"}), + ("success", {"decision": "skip", "reason": "closed"}), + ("failure", PUSH), + ("failure", None), + ("skipped", None), + ("cancelled", None), + ): + with self.subTest(result=result, decision=decision): + self.assertFalse(runs("fire", needs(PUSH, result, decision))) + + def test_a_skip_never_fires(self): + self.assertFalse(runs("fire", needs(SKIP))) + + def test_nothing_fires_in_a_cancelled_run_or_after_a_failed_decide_job(self): + self.assertFalse(runs("fire", needs(READY), cancelled=True)) + self.assertFalse(runs("fire", needs(PUSH, "success", PUSH), cancelled=True)) + self.assertFalse(runs("fire", needs(READY, decide_result="failure"))) + + def test_it_and_the_react_job_check_for_cancellation_not_success(self): + # A condition with no status function gets GitHub's success(), which is false once any job before it was + # skipped, as the settle job is for every kind but Push: the fire and react jobs would then never run. + for job in ("fire", "react"): + with self.subTest(job=job): + self.assertTrue(_yq(f".jobs.{job}.if").strip().startswith("${{ !cancelled()")) + + def test_it_sends_the_decide_jobs_decision(self): + # The settle job passes a Push request on unchanged, so the request text is always the decide job's. + self.assertEqual(step_field("fire", "send", ".env.DECISION"), "${{ needs.decide.outputs.decision }}") + + +class ReactJobTest(unittest.TestCase): + def context(self, sent="true", fire_result="success", decision=COMMENT): + fire = {"result": fire_result, "outputs": {"sent": sent} if sent else {}} + return needs(decision, fire=fire) + + def test_a_sent_comment_command_gets_its_reaction_though_the_settle_job_was_skipped(self): + self.assertTrue(runs("react", self.context())) + + def test_no_reaction_without_a_sent_request_or_in_a_cancelled_run(self): + self.assertFalse(runs("react", self.context(sent=""))) + self.assertFalse(runs("react", self.context(sent="", fire_result="skipped"))) + self.assertFalse(runs("react", self.context(), cancelled=True)) + + def test_no_reaction_for_a_request_that_does_not_ask_for_one(self): + for decision in (READY, PUSH, REQUESTED): + with self.subTest(kind=decision["kind"]): + self.assertFalse(runs("react", self.context(decision=decision))) + + +class DecisionOutputTest(unittest.TestCase): + def output(self, context): + value = _yq(".on.workflow_call.outputs.decision.value").strip() + jobs = {name: {"outputs": job["outputs"]} for name, job in context.items()} + return Expression(value, {"jobs": jobs}).render() + + def test_it_is_the_settle_jobs_decision_for_a_push(self): + for decision in (PUSH, SUPERSEDED, SETTLE_FAILED): + with self.subTest(decision=decision): + self.assertEqual(self.output(needs(PUSH, "success", decision)), compact(decision)) + + def test_it_is_the_settle_check_failed_skip_for_a_push_whose_settle_job_left_no_output(self): + # Such as a settle job whose runner was lost: the decide job's fire must not stand, as fire was skipped. + context = needs(PUSH, "failure") + context["settle"]["outputs"] = {"decision": ""} + self.assertEqual(self.output(context), compact(SETTLE_FAILED)) + + def test_it_is_the_decide_jobs_decision_for_every_other_kind_and_a_skip(self): + for decision in (READY, COMMENT, REQUESTED, SKIP): + with self.subTest(decision=decision): + self.assertEqual(self.output(needs(decision)), compact(decision)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_verify.py b/tests/test_verify.py index 8b60e12..9d3c40a 100644 --- a/tests/test_verify.py +++ b/tests/test_verify.py @@ -633,6 +633,103 @@ def test_a_decision_with_no_pull_request_number_fails_without_reading_comments(s self.assertEqual(self.stub.requests, []) +PULL_PATH = "/repos/cipherstash/example/pulls/42" +PUSHED = "2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e" +NEWER = "3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f" +# The pull request as each settle skip leaves it: a newer head, a draft, or closed. +SETTLED_STATE = { + "superseded": {"state": "open", "draft": False, "head": {"sha": NEWER}}, + "draft": {"state": "open", "draft": True, "head": {"sha": PUSHED}}, + "closed": {"state": "closed", "draft": False, "head": {"sha": PUSHED}}, +} + + +class GivenAPushThatTheSettleWaitSkipped(VerifyTest): + """A push whose request a newer push superseded during the settle wait, or whose pull request was made a draft or + closed then, is not reviewed, by design. The final decision alone cannot say which job skipped the push, so the + step also reads the settle job's own decision (SETTLE_DECISION), and passes only a skip the settle job made. It + then reads the pull request and passes only when it is in the state the skip names, so a settle wait that skips + every push fails.""" + + def settled(self, reason, pull, **overrides): + skip = json.dumps({"decision": "skip", "reason": reason}) + env = { + "EVENT_ACTION": "synchronize", + "SENT": "", + "DECISION": skip, + "SETTLE_DECISION": skip, + "PULL_REQUEST_NUMBER": "42", + "PUSHED_COMMIT": PUSHED, + **overrides, + } + return self.verify(routes={PULL_PATH: (200, json.dumps(pull))}, **env) + + def test_a_skip_passes_when_the_pull_request_is_in_the_state_it_names(self): + for reason, pull in SETTLED_STATE.items(): + with self.subTest(reason=reason): + result = self.settled(reason, pull) + self.assert_passed(result) + self.assertEqual([path for _, path, _ in self.stub.requests], [PULL_PATH]) + self.assertIn(f"Self-test: passed. The push was not reviewed ({reason})", result.summary) + notice = f"::notice title=Push not reviewed::The settle wait skipped the push ({reason})" + self.assertIn(notice, result.stdout) + + def test_a_skip_fails_when_the_pull_request_is_not_in_the_state_it_names(self): + unchanged = {"state": "open", "draft": False, "head": {"sha": PUSHED}} + for reason in SETTLED_STATE: + with self.subTest(reason=reason): + result = self.settled(reason, unchanged) + self.assert_failed(result, f"skipped the push as {reason}") + + def test_a_skip_fails_when_the_pull_request_cannot_be_read(self): + for reason in SETTLED_STATE: + with self.subTest(reason=reason): + skip = json.dumps({"decision": "skip", "reason": reason}) + result = self.verify( + EVENT_ACTION="synchronize", SENT="", DECISION=skip, SETTLE_DECISION=skip, + PULL_REQUEST_NUMBER="42", PUSHED_COMMIT=PUSHED, + ) + self.assert_failed(result, "when asked for pull request #42") + + def test_a_skip_fails_without_the_pushed_commit_or_the_pull_request_number(self): + for name, value in (("PUSHED_COMMIT", ""), ("PULL_REQUEST_NUMBER", ""), ("PULL_REQUEST_NUMBER", "42/../1")): + with self.subTest(name=name, value=value): + result = self.settled("superseded", SETTLED_STATE["superseded"], **{name: value}) + self.assert_failed(result, name) + + def test_a_draft_closed_or_superseded_skip_that_the_settle_job_did_not_make_fails(self): + # The decide job's skip: the settle job did not run, so its output is empty. Or the settle job's decision is + # not the final one. Either is a fault in the request decision or the review workflow, not the settle wait. + for reason in ("superseded", "draft", "closed"): + for settled in ("", "not json", json.dumps({"decision": "skip", "reason": "settle-check-failed"})): + with self.subTest(reason=reason, settled=settled): + skip = json.dumps({"decision": "skip", "reason": reason}) + result = self.verify(EVENT_ACTION="synchronize", DECISION=skip, SETTLE_DECISION=settled) + self.assert_failed(result, f"decided not to request a review ({reason})") + self.assertEqual(self.stub.requests, []) + + def test_a_draft_or_closed_skip_with_no_settle_decision_given_fails(self): + for reason in ("draft", "closed"): + with self.subTest(reason=reason): + skip = json.dumps({"decision": "skip", "reason": reason}) + result = self.verify(EVENT_ACTION="synchronize", DECISION=skip) + self.assert_failed(result, f"decided not to request a review ({reason})") + + def test_any_other_skip_of_a_push_still_fails(self): + for reason in ("settle-check-failed", "not-a-team-member", "bot", "decision-failed"): + with self.subTest(reason=reason): + skip = json.dumps({"decision": "skip", "reason": reason}) + result = self.verify(EVENT_ACTION="synchronize", DECISION=skip) + self.assert_failed(result, f"decided not to request a review ({reason})") + + def test_a_superseded_skip_of_any_other_event_still_fails(self): + for action in ("opened", "ready_for_review", "review_requested"): + with self.subTest(action=action): + skip = json.dumps({"decision": "skip", "reason": "superseded"}) + result = self.verify(EVENT_ACTION=action, DECISION=skip) + self.assert_failed(result, "decided not to request a review (superseded)") + + class GivenTheRunIsNotKnown(VerifyTest): def test_without_the_runs_details_the_step_fails_without_reading_comments(self): for name in ("GITHUB_SERVER_URL", "GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT"):