You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by GitBox <gi...@apache.org> on 2022/03/02 15:01:06 UTC

[GitHub] [beam] damccorm opened a new pull request #16985: Add ability to get metrics on pr-bot performance

damccorm opened a new pull request #16985:
URL: https://github.com/apache/beam/pull/16985


   Right now, we don't have a well defined automated system for staying on top of pull request reviews - we rely on contributors being able to find the correct OWNERS file and committers manually triaging/calling attention to old pull requests. This is the continuation of an effort to improve our automation around this. [Design doc for the full effort here](https://docs.google.com/document/d/1FhRPRD6VXkYlLAPhNfZB7y2Yese2FCWBzjx67d3TjBo/edit#).
   
   This specific change is mostly independent of the rest - it gets metrics about how well we are handling prs and outputs them into a CSV. The generated output columns are: 
   
   - Bucket start (bucketed by merge time)
   - Prs Completed
   - Prs completed by first time contributors
   - Average time in minutes to first review
   - Average time in minutes to first review for new contributors
   - Average time in minutes from pr creation to completion
   - Total number of reviewers
   - Total number of committers performing reviews
   - Total number of non-committers performing reviews
   - Gini index (fairness) of committers performing reviews
   - Average time in minutes from committer assignment to pr merge
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] [**Choose reviewer(s)**](https://beam.apache.org/contribute/#make-your-change) and mention them in a comment (`R: @username`).
    - [x] Format the pull request title like `[BEAM-XXX] Fixes bug in ApproximateQuantiles`, where you replace `BEAM-XXX` with the appropriate JIRA issue, if applicable. This will automatically link the pull request to the issue.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [x] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://beam.apache.org/contribute/#make-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/workflows/Build%20python%20source%20distribution%20and%20wheels/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/workflows/Python%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/workflows/Java%20Tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819026557



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;
+  while (bucketStart.getTime() > pullStat.mergedDate.getTime()) {
+    bucketStart.setDate(bucketStart.getDate() - 7);
+  }
+
+  return bucketStart.getTime();
+}
+
+function distinctReviewers(pullStats: PrStats[]): string[] {
+  let users: Set<string> = new Set();
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (user) => {
+        users.add(user);
+      }
+    );
+  });
+  return Array.from(users);
+}
+
+async function committersFromReviewers(users: string[]): Promise<string[]> {
+  let committers: string[] = [];
+  for (let i = 0; i < users.length; i++) {
+    let user = users[i];
+    if (await github.checkIfCommitter(user)) {
+      committers.push(user);
+    }
+  }
+  return committers;
+}
+
+function averageTimeFromCommitterAssignmentToPrMerge(
+  pullStats: PrStats[],
+  committers: string[]
+): number {
+  if (committers.length === 0) {
+    return 0;
+  }
+  let numCommitterReviews = 0;
+  let totalTimeFromAssignToMerge = 0;
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          numCommitterReviews++;
+          totalTimeFromAssignToMerge +=
+            pullStat.timeFromReviewersMentionedToCompletion[reviewer];
+        }
+      }
+    );
+  });
+  return totalTimeFromAssignToMerge / numCommitterReviews;
+}
+
+// Calculates a gini index of inequality for reviews.
+// 0 is perfectly equally distributed, 1 is inequally distributed (with 1 person having all reviews)
+function getGiniIndexForCommitterReviews(
+  pullStats: PrStats[],
+  committers: string[]
+) {
+  let reviewsPerCommitter: { [key: string]: number } = {};
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          if (reviewer in reviewsPerCommitter) {
+            reviewsPerCommitter[reviewer]++;
+          } else {
+            reviewsPerCommitter[reviewer] = 1;
+          }
+        }
+      }
+    );
+  });
+  let reviewCounts = Object.values(reviewsPerCommitter);
+  reviewCounts.sort();
+  let giniNumerator = 0;
+  let giniDenominator = 0;
+  const n = reviewCounts.length;
+  for (let i = 1; i <= reviewCounts.length; i++) {
+    let yi = reviewCounts[i - 1];
+    giniNumerator += (n + 1 - i) * yi;
+    giniDenominator += yi;
+  }
+  return (1 / n) * (n + 1 - (2 * giniNumerator) / giniDenominator);
+}
+
+async function aggregateStatsForBucket(
+  pullStats: PrStats[]
+): Promise<AggregatedMetrics> {
+  const reviewers = distinctReviewers(pullStats);
+  const committers = await committersFromReviewers(reviewers);
+  const firstTimePrs = pullStats.filter(
+    (pullStat) => pullStat.firstTimeContribution
+  );
+  let averageTimeToNewContributorFirstReview = 0;
+  if (firstTimePrs.length > 0) {
+    averageTimeToNewContributorFirstReview =
+      firstTimePrs.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeToFirstReview,
+        0
+      ) / firstTimePrs.length;
+  }
+  return {
+    prsCompleted: pullStats.length,
+    prsCompletedByNewContributors: firstTimePrs.length,
+    averageTimeToFirstReview:
+      pullStats.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeToFirstReview,
+        0
+      ) / pullStats.length,
+    averageTimeToNewContributorFirstReview:
+      averageTimeToNewContributorFirstReview,
+    averageTimeCreationToCompletion:
+      pullStats.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeFromCreationToCompletion,
+        0
+      ) / pullStats.length,
+    numUsersPerformingReviews: reviewers.length,
+    numCommittersPerformingReviews: committers.length,
+    numNonCommittersPerformingReviews: reviewers.length - committers.length,
+    giniIndexCommittersPerformingReviews: getGiniIndexForCommitterReviews(
+      pullStats,
+      committers
+    ),
+    averageTimeFromCommitterAssignmentToPrMerge:
+      averageTimeFromCommitterAssignmentToPrMerge(pullStats, committers),
+  };
+}
+
+function convertMsToRoundedMinutes(milliseconds: number): number {
+  return Math.floor(milliseconds / 60000);
+}
+
+async function reportMetrics(statBuckets: { [key: number]: PrStats[] }) {
+  console.log("---------------------------------");
+  console.log("PR Stats");
+  console.log("---------------------------------");
+  let csvOutput = "";
+  csvOutput +=
+    "Bucket start (bucketed by merge time),PRs Completed,PRs completed by first time contributors,Average time in minutes to first review,Average time in minutes to first review for new contributors,Average time in minutes from PR creation to completion,Total number of reviewers,Total number of committers performing reviews,Total number of non-committers performing reviews,Gini index (fairness) of committers performing reviews,Average time in minutes from committer assignment to PR merge";
+  const startDates = Object.keys(statBuckets);
+  for (let i = 0; i < startDates.length; i++) {
+    let startDate = startDates[i];
+    let aggregatedStats = await aggregateStatsForBucket(statBuckets[startDate]);
+    console.log();
+
+    const bucketStart = new Date(parseInt(startDate));
+    console.log("Bucket start:", bucketStart);
+    csvOutput += `\n${bucketStart.toDateString()}`;
+
+    console.log("PRs completed:", aggregatedStats.prsCompleted);
+    csvOutput += `,${aggregatedStats.prsCompleted}`;
+
+    console.log(
+      "PRs completed by first time contributors:",
+      aggregatedStats.prsCompletedByNewContributors
+    );
+    csvOutput += `,${aggregatedStats.prsCompletedByNewContributors}`;
+
+    console.log(
+      "Average time in minutes to first review:",
+      convertMsToRoundedMinutes(aggregatedStats.averageTimeToFirstReview)
+    );
+    csvOutput += `,${convertMsToRoundedMinutes(
+      aggregatedStats.averageTimeToFirstReview
+    )}`;
+
+    console.log(
+      "Average time in minutes to first review for new contributors:",
+      convertMsToRoundedMinutes(
+        aggregatedStats.averageTimeToNewContributorFirstReview
+      )
+    );
+    csvOutput += `,${convertMsToRoundedMinutes(
+      aggregatedStats.averageTimeToNewContributorFirstReview
+    )}`;
+
+    console.log(
+      "Average time in minutes from PR creation to completion:",
+      convertMsToRoundedMinutes(aggregatedStats.averageTimeCreationToCompletion)
+    );
+    csvOutput += `,${convertMsToRoundedMinutes(
+      aggregatedStats.averageTimeCreationToCompletion
+    )}`;
+
+    console.log(
+      "Total number of reviewers:",
+      aggregatedStats.numUsersPerformingReviews
+    );
+    csvOutput += `,${aggregatedStats.numUsersPerformingReviews}`;
+
+    console.log(
+      "Total number of committers performing reviews:",
+      aggregatedStats.numCommittersPerformingReviews
+    );
+    csvOutput += `,${aggregatedStats.numCommittersPerformingReviews}`;
+
+    console.log(
+      "Total number of non-committers performing reviews:",
+      aggregatedStats.numNonCommittersPerformingReviews
+    );
+    csvOutput += `,${aggregatedStats.numNonCommittersPerformingReviews}`;
+
+    console.log(
+      "Gini index (fairness) of committers performing reviews:",
+      aggregatedStats.giniIndexCommittersPerformingReviews
+    );
+    csvOutput += `,${aggregatedStats.giniIndexCommittersPerformingReviews}`;
+
+    console.log(
+      "Average time in minutes from committer assignment to PR merge:",
+      convertMsToRoundedMinutes(
+        aggregatedStats.averageTimeFromCommitterAssignmentToPrMerge
+      )
+    );
+    csvOutput += `,${convertMsToRoundedMinutes(
+      aggregatedStats.averageTimeFromCommitterAssignmentToPrMerge
+    )}`;
+  }
+  fs.writeFileSync(PATH_TO_METRICS_CSV, csvOutput);
+  console.log(`Output written to ${PATH_TO_METRICS_CSV}`);
+}
+
+async function gatherMetrics() {
+  // We will only aggregate metrics from the last 90 days,
+  // but will look further back to determine if this is a user's first contribution
+  const pullsFromLastYear = await getCompletedPullsFromLastYear();
+  let cutoffDate = new Date();
+  cutoffDate.setDate(cutoffDate.getDate() - 90);
+
+  let pullStats: PrStats[] = [];
+  console.log("Extracting stats from pulls - this may take a while");
+  for (let i = 0; i < pullsFromLastYear.length; i++) {
+    let pull = pullsFromLastYear[i];
+    if (new Date(pull.created_at) > cutoffDate && pull.merged_at) {
+      pullStats.push(await extractPrStats(pull, pullsFromLastYear));
+    }
+    if (i % 10 === 0) {
+      process.stdout.write(".");
+    }
+  }
+
+  console.log("\nDone extracting stats, formatting results");
+
+  let statBuckets: { [key: number]: PrStats[] } = {};
+  let bucketEnd = new Date();
+  bucketEnd.setUTCHours(23, 59, 59, 999);
+  pullStats.forEach((pullStat) => {
+    let bucketStart = getMetricBucketStartDate(pullStat, bucketEnd);
+    if (bucketStart in statBuckets) {
+      statBuckets[bucketStart].push(pullStat);
+    } else {
+      statBuckets[bucketStart] = [pullStat];
+    }
+  });
+  await reportMetrics(statBuckets);
+}
+
+gatherMetrics();
+
+export {};

Review comment:
       This is a common pattern for github actions, we chatted about it and decided its ok to keep




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819005407



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;

Review comment:
       Sure, I think its a little cleaner

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {

Review comment:
       That's true - the whole if statement was actually just useless




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819017645



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;
+  while (bucketStart.getTime() > pullStat.mergedDate.getTime()) {
+    bucketStart.setDate(bucketStart.getDate() - 7);
+  }
+
+  return bucketStart.getTime();
+}
+
+function distinctReviewers(pullStats: PrStats[]): string[] {
+  let users: Set<string> = new Set();
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (user) => {
+        users.add(user);
+      }
+    );
+  });
+  return Array.from(users);
+}
+
+async function committersFromReviewers(users: string[]): Promise<string[]> {
+  let committers: string[] = [];
+  for (let i = 0; i < users.length; i++) {
+    let user = users[i];
+    if (await github.checkIfCommitter(user)) {
+      committers.push(user);
+    }
+  }
+  return committers;
+}
+
+function averageTimeFromCommitterAssignmentToPrMerge(
+  pullStats: PrStats[],
+  committers: string[]
+): number {
+  if (committers.length === 0) {
+    return 0;
+  }
+  let numCommitterReviews = 0;
+  let totalTimeFromAssignToMerge = 0;
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          numCommitterReviews++;
+          totalTimeFromAssignToMerge +=
+            pullStat.timeFromReviewersMentionedToCompletion[reviewer];
+        }
+      }
+    );
+  });
+  return totalTimeFromAssignToMerge / numCommitterReviews;

Review comment:
       Good catch




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r820108334



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,528 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date();
+  cutoffDate.setFullYear(new Date().getFullYear() - 1);
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page++;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries++;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  return !pullsFromLastYear.some(
+    (pullFromLastYear) =>
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+  );
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+
+  const firstReviewed = reviews.find(
+    (review) => review.user.login == pull.user.login

Review comment:
       Good catch - yes, that was a bad update in response to comments 😞 I merged the suggestion in




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] youngoli commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
youngoli commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r820022640



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,528 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date();
+  cutoffDate.setFullYear(new Date().getFullYear() - 1);
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page++;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries++;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  return !pullsFromLastYear.some(
+    (pullFromLastYear) =>
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+  );
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+
+  const firstReviewed = reviews.find(
+    (review) => review.user.login == pull.user.login

Review comment:
       Shouldn't this be the following?
   ```suggestion
       (review) => review.user.login != pull.user.login
   ```




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819036306



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};

Review comment:
       I gave it a try and didn't find a significant difference in readability, and given that I didn't feel inclined to plumb it all the way through. Let me know if you disagree:
   
   ```
   
     let timeToCompletionPerReviewer = new Map();
     for (const comment of comments) {
       const reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
       const commentCreationDate = new Date(comment.created_at);
       const timeToCompletion =
         mergedDate.getTime() - commentCreationDate.getTime();
       for (const reviewer of reviewersTagged) {
         if (reviewer in timeToCompletionPerReviewer) {
           timeToCompletionPerReviewer.set(reviewer, Math.max(
             timeToCompletion,
             timeToCompletionPerReviewer.get(reviewer)
           ));
         } else {
           timeToCompletionPerReviewer.set(reviewer, timeToCompletion);
         }
       }
     }
   ```




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] youngoli merged pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
youngoli merged pull request #16985:
URL: https://github.com/apache/beam/pull/16985


   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819020752



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;
+  while (bucketStart.getTime() > pullStat.mergedDate.getTime()) {
+    bucketStart.setDate(bucketStart.getDate() - 7);
+  }
+
+  return bucketStart.getTime();
+}
+
+function distinctReviewers(pullStats: PrStats[]): string[] {
+  let users: Set<string> = new Set();
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (user) => {
+        users.add(user);
+      }
+    );
+  });
+  return Array.from(users);
+}
+
+async function committersFromReviewers(users: string[]): Promise<string[]> {
+  let committers: string[] = [];
+  for (let i = 0; i < users.length; i++) {
+    let user = users[i];
+    if (await github.checkIfCommitter(user)) {
+      committers.push(user);
+    }
+  }
+  return committers;
+}
+
+function averageTimeFromCommitterAssignmentToPrMerge(
+  pullStats: PrStats[],
+  committers: string[]
+): number {
+  if (committers.length === 0) {
+    return 0;
+  }
+  let numCommitterReviews = 0;
+  let totalTimeFromAssignToMerge = 0;
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          numCommitterReviews++;
+          totalTimeFromAssignToMerge +=
+            pullStat.timeFromReviewersMentionedToCompletion[reviewer];
+        }
+      }
+    );
+  });
+  return totalTimeFromAssignToMerge / numCommitterReviews;
+}
+
+// Calculates a gini index of inequality for reviews.
+// 0 is perfectly equally distributed, 1 is inequally distributed (with 1 person having all reviews)
+function getGiniIndexForCommitterReviews(
+  pullStats: PrStats[],
+  committers: string[]
+) {
+  let reviewsPerCommitter: { [key: string]: number } = {};
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          if (reviewer in reviewsPerCommitter) {
+            reviewsPerCommitter[reviewer]++;
+          } else {
+            reviewsPerCommitter[reviewer] = 1;
+          }

Review comment:
       I tried it, I don't love it from a readability standpoint (though I'll admit I'm not a huge fan of the ternary approach in most cases)
   
   ```
   reviewsPerCommitter[reviewer] =
               reviewer in reviewsPerCommitter
                 ? reviewsPerCommitter[reviewer] + 1
                 : 1;
   ```




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819030820



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(

Review comment:
       I think it is because setFullYear returns a number. With that said, I can simplify by just running setFullYear on an already existing cutoffDate




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on pull request #16985:
URL: https://github.com/apache/beam/pull/16985#issuecomment-1058462624


   R: @youngoli for final approval


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819013520



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;

Review comment:
       IMOit helps readability for exactly what the await is waiting on - I can cut it if you feel strongly about it

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;

Review comment:
       IMO it helps readability for exactly what the await is waiting on - I can cut it if you feel strongly about it

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;

Review comment:
       IMO it helps readability for exactly what the await is waiting on




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on pull request #16985: Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on pull request #16985:
URL: https://github.com/apache/beam/pull/16985#issuecomment-1057031275


   R: @KonradJanica would you mind taking a look at another one - this one is mostly isolated from the others but is pushing towards the same overarching goal of getting/measuring a working pr bot


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] KonradJanica commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
KonradJanica commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r818927401



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(

Review comment:
       I believe the outter `new Date` constructor is not needed.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;

Review comment:
       Perhaps use [find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) to save some lines.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}

Review comment:
       Could we use [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) here instead? E.g. body.split(' @').

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {

Review comment:
       ditto `forEach` => `of`

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;
+  while (bucketStart.getTime() > pullStat.mergedDate.getTime()) {
+    bucketStart.setDate(bucketStart.getDate() - 7);
+  }
+
+  return bucketStart.getTime();
+}
+
+function distinctReviewers(pullStats: PrStats[]): string[] {
+  let users: Set<string> = new Set();
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (user) => {
+        users.add(user);
+      }
+    );
+  });
+  return Array.from(users);
+}
+
+async function committersFromReviewers(users: string[]): Promise<string[]> {
+  let committers: string[] = [];
+  for (let i = 0; i < users.length; i++) {
+    let user = users[i];
+    if (await github.checkIfCommitter(user)) {
+      committers.push(user);
+    }
+  }
+  return committers;
+}

Review comment:
       All loops in this block will be cleaner using the `for (const foo of bar)` syntax.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;
+  while (bucketStart.getTime() > pullStat.mergedDate.getTime()) {
+    bucketStart.setDate(bucketStart.getDate() - 7);
+  }
+
+  return bucketStart.getTime();
+}
+
+function distinctReviewers(pullStats: PrStats[]): string[] {
+  let users: Set<string> = new Set();
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (user) => {
+        users.add(user);
+      }
+    );
+  });
+  return Array.from(users);
+}
+
+async function committersFromReviewers(users: string[]): Promise<string[]> {
+  let committers: string[] = [];
+  for (let i = 0; i < users.length; i++) {
+    let user = users[i];
+    if (await github.checkIfCommitter(user)) {
+      committers.push(user);
+    }
+  }
+  return committers;
+}
+
+function averageTimeFromCommitterAssignmentToPrMerge(
+  pullStats: PrStats[],
+  committers: string[]
+): number {
+  if (committers.length === 0) {
+    return 0;
+  }
+  let numCommitterReviews = 0;
+  let totalTimeFromAssignToMerge = 0;
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          numCommitterReviews++;
+          totalTimeFromAssignToMerge +=
+            pullStat.timeFromReviewersMentionedToCompletion[reviewer];
+        }
+      }
+    );
+  });
+  return totalTimeFromAssignToMerge / numCommitterReviews;
+}
+
+// Calculates a gini index of inequality for reviews.
+// 0 is perfectly equally distributed, 1 is inequally distributed (with 1 person having all reviews)
+function getGiniIndexForCommitterReviews(
+  pullStats: PrStats[],
+  committers: string[]
+) {
+  let reviewsPerCommitter: { [key: string]: number } = {};
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          if (reviewer in reviewsPerCommitter) {
+            reviewsPerCommitter[reviewer]++;
+          } else {
+            reviewsPerCommitter[reviewer] = 1;
+          }

Review comment:
       Perhaps a ternary statement is cleaner here.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};

Review comment:
       Perhaps a [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) would be more readable.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);

Review comment:
       all these `let` => `const`.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {

Review comment:
       `for (const comment of comments)` syntax is preferred over forEach.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}

Review comment:
       Perhaps using [some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some), but reversing the condition, would be cleaner.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;

Review comment:
       `++retries;`

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {

Review comment:
       This will never be true.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;

Review comment:
       `let` => `const`.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;

Review comment:
       `++page;`

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {

Review comment:
       `let` => `const`

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;

Review comment:
       Are the outer brackets necessary?

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;
+  while (bucketStart.getTime() > pullStat.mergedDate.getTime()) {
+    bucketStart.setDate(bucketStart.getDate() - 7);
+  }
+
+  return bucketStart.getTime();
+}
+
+function distinctReviewers(pullStats: PrStats[]): string[] {
+  let users: Set<string> = new Set();
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (user) => {
+        users.add(user);
+      }
+    );
+  });
+  return Array.from(users);
+}
+
+async function committersFromReviewers(users: string[]): Promise<string[]> {
+  let committers: string[] = [];
+  for (let i = 0; i < users.length; i++) {
+    let user = users[i];
+    if (await github.checkIfCommitter(user)) {
+      committers.push(user);
+    }
+  }
+  return committers;
+}
+
+function averageTimeFromCommitterAssignmentToPrMerge(
+  pullStats: PrStats[],
+  committers: string[]
+): number {
+  if (committers.length === 0) {
+    return 0;
+  }
+  let numCommitterReviews = 0;
+  let totalTimeFromAssignToMerge = 0;
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          numCommitterReviews++;
+          totalTimeFromAssignToMerge +=
+            pullStat.timeFromReviewersMentionedToCompletion[reviewer];
+        }
+      }
+    );
+  });
+  return totalTimeFromAssignToMerge / numCommitterReviews;

Review comment:
       If committers is not empty but pullState.timeFromReviewersMentionedToCompletion is empty, `numCommitterReviews` could be 0 resulting in `NaN`.

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;
+  while (bucketStart.getTime() > pullStat.mergedDate.getTime()) {
+    bucketStart.setDate(bucketStart.getDate() - 7);
+  }
+
+  return bucketStart.getTime();
+}
+
+function distinctReviewers(pullStats: PrStats[]): string[] {
+  let users: Set<string> = new Set();
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (user) => {
+        users.add(user);
+      }
+    );
+  });
+  return Array.from(users);
+}
+
+async function committersFromReviewers(users: string[]): Promise<string[]> {
+  let committers: string[] = [];
+  for (let i = 0; i < users.length; i++) {
+    let user = users[i];
+    if (await github.checkIfCommitter(user)) {
+      committers.push(user);
+    }
+  }
+  return committers;
+}
+
+function averageTimeFromCommitterAssignmentToPrMerge(
+  pullStats: PrStats[],
+  committers: string[]
+): number {
+  if (committers.length === 0) {
+    return 0;
+  }
+  let numCommitterReviews = 0;
+  let totalTimeFromAssignToMerge = 0;
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          numCommitterReviews++;
+          totalTimeFromAssignToMerge +=
+            pullStat.timeFromReviewersMentionedToCompletion[reviewer];
+        }
+      }
+    );
+  });
+  return totalTimeFromAssignToMerge / numCommitterReviews;
+}
+
+// Calculates a gini index of inequality for reviews.
+// 0 is perfectly equally distributed, 1 is inequally distributed (with 1 person having all reviews)
+function getGiniIndexForCommitterReviews(
+  pullStats: PrStats[],
+  committers: string[]
+) {
+  let reviewsPerCommitter: { [key: string]: number } = {};
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          if (reviewer in reviewsPerCommitter) {
+            reviewsPerCommitter[reviewer]++;
+          } else {
+            reviewsPerCommitter[reviewer] = 1;
+          }
+        }
+      }
+    );
+  });
+  let reviewCounts = Object.values(reviewsPerCommitter);
+  reviewCounts.sort();
+  let giniNumerator = 0;
+  let giniDenominator = 0;
+  const n = reviewCounts.length;
+  for (let i = 1; i <= reviewCounts.length; i++) {
+    let yi = reviewCounts[i - 1];
+    giniNumerator += (n + 1 - i) * yi;
+    giniDenominator += yi;
+  }
+  return (1 / n) * (n + 1 - (2 * giniNumerator) / giniDenominator);
+}
+
+async function aggregateStatsForBucket(
+  pullStats: PrStats[]
+): Promise<AggregatedMetrics> {
+  const reviewers = distinctReviewers(pullStats);
+  const committers = await committersFromReviewers(reviewers);
+  const firstTimePrs = pullStats.filter(
+    (pullStat) => pullStat.firstTimeContribution
+  );
+  let averageTimeToNewContributorFirstReview = 0;
+  if (firstTimePrs.length > 0) {
+    averageTimeToNewContributorFirstReview =
+      firstTimePrs.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeToFirstReview,
+        0
+      ) / firstTimePrs.length;
+  }
+  return {
+    prsCompleted: pullStats.length,
+    prsCompletedByNewContributors: firstTimePrs.length,
+    averageTimeToFirstReview:
+      pullStats.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeToFirstReview,
+        0
+      ) / pullStats.length,
+    averageTimeToNewContributorFirstReview:
+      averageTimeToNewContributorFirstReview,
+    averageTimeCreationToCompletion:
+      pullStats.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeFromCreationToCompletion,
+        0
+      ) / pullStats.length,
+    numUsersPerformingReviews: reviewers.length,
+    numCommittersPerformingReviews: committers.length,
+    numNonCommittersPerformingReviews: reviewers.length - committers.length,
+    giniIndexCommittersPerformingReviews: getGiniIndexForCommitterReviews(
+      pullStats,
+      committers
+    ),
+    averageTimeFromCommitterAssignmentToPrMerge:
+      averageTimeFromCommitterAssignmentToPrMerge(pullStats, committers),
+  };
+}
+
+function convertMsToRoundedMinutes(milliseconds: number): number {
+  return Math.floor(milliseconds / 60000);

Review comment:
       `60000` => `60_000`

##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {
+    return [];
+  }
+  let usernames: string[] = [];
+  let usernameIndex = 0;
+  while (body.indexOf(" @", usernameIndex) > -1) {
+    usernameIndex = body.indexOf(" @", usernameIndex) + 2;
+    let curUsername = "";
+    while (
+      usernameIndex < body.length &&
+      body[usernameIndex].match(/^[0-9a-z]+$/)
+    ) {
+      curUsername += body[usernameIndex];
+      usernameIndex += 1;
+    }
+    // Filter out username from PR template
+    if (curUsername && curUsername != "username") {
+      usernames.push(curUsername);
+    }
+  }
+  return usernames;
+}
+
+// Returns a dictionary mapping reviewers to the amount of time from their first comment to pr completion.
+function getTimeFromReviewerMentionedToCompletion(
+  pull: any,
+  comments: any[],
+  reviewComments: any[],
+  mergedDate: Date
+): { [key: string]: number } {
+  comments = comments.concat(reviewComments);
+  comments.push(pull);
+  let timeToCompletionPerReviewer = {};
+  comments.forEach((comment) => {
+    let reviewersTagged = extractReviewersTaggedFromCommentBody(comment.body);
+    let commentCreationDate = new Date(comment.created_at);
+    let timeToCompletion = mergedDate.getTime() - commentCreationDate.getTime();
+    reviewersTagged.forEach((reviewer) => {
+      if (reviewer in timeToCompletionPerReviewer) {
+        timeToCompletionPerReviewer[reviewer] = Math.max(
+          timeToCompletion,
+          timeToCompletionPerReviewer[reviewer]
+        );
+      } else {
+        timeToCompletionPerReviewer[reviewer] = timeToCompletion;
+      }
+    });
+  });
+
+  return timeToCompletionPerReviewer;
+}
+
+async function extractPrStats(
+  pull: any,
+  pullsFromLastYear: any[]
+): Promise<PrStats> {
+  const githubClient = github.getGitHubClient();
+  const creationDate = new Date(pull.created_at);
+  const mergedDate = new Date(pull.merged_at);
+  const reviews = (
+    await githubClient.rest.pulls.listReviews({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  // GitHub has a concept of review comments (must be part of a review) and issue comments on a repo, so we need to look at both
+  const comments = (
+    await githubClient.rest.issues.listComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      issue_number: pull.number,
+    })
+  ).data;
+  const reviewComments = (
+    await githubClient.rest.pulls.listReviewComments({
+      owner: REPO_OWNER,
+      repo: REPO,
+      pull_number: pull.number,
+    })
+  ).data;
+  let prStats: PrStats = {
+    firstTimeContribution: checkIfFirstTimeContributor(pull, pullsFromLastYear),
+    timeToFirstReview: getTimeToFirstReview(
+      pull,
+      comments,
+      reviews,
+      creationDate,
+      mergedDate
+    ),
+    timeFromCreationToCompletion: mergedDate.getTime() - creationDate.getTime(),
+    timeFromReviewersMentionedToCompletion:
+      getTimeFromReviewerMentionedToCompletion(
+        pull,
+        comments,
+        reviewComments,
+        mergedDate
+      ),
+    mergedDate: mergedDate,
+  };
+
+  return prStats;
+}
+
+function getMetricBucketStartDate(pullStat: PrStats, bucketEnd: Date): number {
+  let bucketStart = bucketEnd;
+  while (bucketStart.getTime() > pullStat.mergedDate.getTime()) {
+    bucketStart.setDate(bucketStart.getDate() - 7);
+  }
+
+  return bucketStart.getTime();
+}
+
+function distinctReviewers(pullStats: PrStats[]): string[] {
+  let users: Set<string> = new Set();
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (user) => {
+        users.add(user);
+      }
+    );
+  });
+  return Array.from(users);
+}
+
+async function committersFromReviewers(users: string[]): Promise<string[]> {
+  let committers: string[] = [];
+  for (let i = 0; i < users.length; i++) {
+    let user = users[i];
+    if (await github.checkIfCommitter(user)) {
+      committers.push(user);
+    }
+  }
+  return committers;
+}
+
+function averageTimeFromCommitterAssignmentToPrMerge(
+  pullStats: PrStats[],
+  committers: string[]
+): number {
+  if (committers.length === 0) {
+    return 0;
+  }
+  let numCommitterReviews = 0;
+  let totalTimeFromAssignToMerge = 0;
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          numCommitterReviews++;
+          totalTimeFromAssignToMerge +=
+            pullStat.timeFromReviewersMentionedToCompletion[reviewer];
+        }
+      }
+    );
+  });
+  return totalTimeFromAssignToMerge / numCommitterReviews;
+}
+
+// Calculates a gini index of inequality for reviews.
+// 0 is perfectly equally distributed, 1 is inequally distributed (with 1 person having all reviews)
+function getGiniIndexForCommitterReviews(
+  pullStats: PrStats[],
+  committers: string[]
+) {
+  let reviewsPerCommitter: { [key: string]: number } = {};
+  pullStats.forEach((pullStat) => {
+    Object.keys(pullStat.timeFromReviewersMentionedToCompletion).forEach(
+      (reviewer) => {
+        if (committers.indexOf(reviewer) > -1) {
+          if (reviewer in reviewsPerCommitter) {
+            reviewsPerCommitter[reviewer]++;
+          } else {
+            reviewsPerCommitter[reviewer] = 1;
+          }
+        }
+      }
+    );
+  });
+  let reviewCounts = Object.values(reviewsPerCommitter);
+  reviewCounts.sort();
+  let giniNumerator = 0;
+  let giniDenominator = 0;
+  const n = reviewCounts.length;
+  for (let i = 1; i <= reviewCounts.length; i++) {
+    let yi = reviewCounts[i - 1];
+    giniNumerator += (n + 1 - i) * yi;
+    giniDenominator += yi;
+  }
+  return (1 / n) * (n + 1 - (2 * giniNumerator) / giniDenominator);
+}
+
+async function aggregateStatsForBucket(
+  pullStats: PrStats[]
+): Promise<AggregatedMetrics> {
+  const reviewers = distinctReviewers(pullStats);
+  const committers = await committersFromReviewers(reviewers);
+  const firstTimePrs = pullStats.filter(
+    (pullStat) => pullStat.firstTimeContribution
+  );
+  let averageTimeToNewContributorFirstReview = 0;
+  if (firstTimePrs.length > 0) {
+    averageTimeToNewContributorFirstReview =
+      firstTimePrs.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeToFirstReview,
+        0
+      ) / firstTimePrs.length;
+  }
+  return {
+    prsCompleted: pullStats.length,
+    prsCompletedByNewContributors: firstTimePrs.length,
+    averageTimeToFirstReview:
+      pullStats.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeToFirstReview,
+        0
+      ) / pullStats.length,
+    averageTimeToNewContributorFirstReview:
+      averageTimeToNewContributorFirstReview,
+    averageTimeCreationToCompletion:
+      pullStats.reduce(
+        (sumTime, prStat) => sumTime + prStat.timeFromCreationToCompletion,
+        0
+      ) / pullStats.length,
+    numUsersPerformingReviews: reviewers.length,
+    numCommittersPerformingReviews: committers.length,
+    numNonCommittersPerformingReviews: reviewers.length - committers.length,
+    giniIndexCommittersPerformingReviews: getGiniIndexForCommitterReviews(
+      pullStats,
+      committers
+    ),
+    averageTimeFromCommitterAssignmentToPrMerge:
+      averageTimeFromCommitterAssignmentToPrMerge(pullStats, committers),
+  };
+}
+
+function convertMsToRoundedMinutes(milliseconds: number): number {
+  return Math.floor(milliseconds / 60000);
+}
+
+async function reportMetrics(statBuckets: { [key: number]: PrStats[] }) {
+  console.log("---------------------------------");
+  console.log("PR Stats");
+  console.log("---------------------------------");
+  let csvOutput = "";
+  csvOutput +=
+    "Bucket start (bucketed by merge time),PRs Completed,PRs completed by first time contributors,Average time in minutes to first review,Average time in minutes to first review for new contributors,Average time in minutes from PR creation to completion,Total number of reviewers,Total number of committers performing reviews,Total number of non-committers performing reviews,Gini index (fairness) of committers performing reviews,Average time in minutes from committer assignment to PR merge";
+  const startDates = Object.keys(statBuckets);
+  for (let i = 0; i < startDates.length; i++) {
+    let startDate = startDates[i];
+    let aggregatedStats = await aggregateStatsForBucket(statBuckets[startDate]);
+    console.log();
+
+    const bucketStart = new Date(parseInt(startDate));
+    console.log("Bucket start:", bucketStart);
+    csvOutput += `\n${bucketStart.toDateString()}`;
+
+    console.log("PRs completed:", aggregatedStats.prsCompleted);
+    csvOutput += `,${aggregatedStats.prsCompleted}`;
+
+    console.log(
+      "PRs completed by first time contributors:",
+      aggregatedStats.prsCompletedByNewContributors
+    );
+    csvOutput += `,${aggregatedStats.prsCompletedByNewContributors}`;
+
+    console.log(
+      "Average time in minutes to first review:",
+      convertMsToRoundedMinutes(aggregatedStats.averageTimeToFirstReview)
+    );
+    csvOutput += `,${convertMsToRoundedMinutes(
+      aggregatedStats.averageTimeToFirstReview
+    )}`;
+
+    console.log(
+      "Average time in minutes to first review for new contributors:",
+      convertMsToRoundedMinutes(
+        aggregatedStats.averageTimeToNewContributorFirstReview
+      )
+    );
+    csvOutput += `,${convertMsToRoundedMinutes(
+      aggregatedStats.averageTimeToNewContributorFirstReview
+    )}`;
+
+    console.log(
+      "Average time in minutes from PR creation to completion:",
+      convertMsToRoundedMinutes(aggregatedStats.averageTimeCreationToCompletion)
+    );
+    csvOutput += `,${convertMsToRoundedMinutes(
+      aggregatedStats.averageTimeCreationToCompletion
+    )}`;
+
+    console.log(
+      "Total number of reviewers:",
+      aggregatedStats.numUsersPerformingReviews
+    );
+    csvOutput += `,${aggregatedStats.numUsersPerformingReviews}`;
+
+    console.log(
+      "Total number of committers performing reviews:",
+      aggregatedStats.numCommittersPerformingReviews
+    );
+    csvOutput += `,${aggregatedStats.numCommittersPerformingReviews}`;
+
+    console.log(
+      "Total number of non-committers performing reviews:",
+      aggregatedStats.numNonCommittersPerformingReviews
+    );
+    csvOutput += `,${aggregatedStats.numNonCommittersPerformingReviews}`;
+
+    console.log(
+      "Gini index (fairness) of committers performing reviews:",
+      aggregatedStats.giniIndexCommittersPerformingReviews
+    );
+    csvOutput += `,${aggregatedStats.giniIndexCommittersPerformingReviews}`;
+
+    console.log(
+      "Average time in minutes from committer assignment to PR merge:",
+      convertMsToRoundedMinutes(
+        aggregatedStats.averageTimeFromCommitterAssignmentToPrMerge
+      )
+    );
+    csvOutput += `,${convertMsToRoundedMinutes(
+      aggregatedStats.averageTimeFromCommitterAssignmentToPrMerge
+    )}`;
+  }
+  fs.writeFileSync(PATH_TO_METRICS_CSV, csvOutput);
+  console.log(`Output written to ${PATH_TO_METRICS_CSV}`);
+}
+
+async function gatherMetrics() {
+  // We will only aggregate metrics from the last 90 days,
+  // but will look further back to determine if this is a user's first contribution
+  const pullsFromLastYear = await getCompletedPullsFromLastYear();
+  let cutoffDate = new Date();
+  cutoffDate.setDate(cutoffDate.getDate() - 90);
+
+  let pullStats: PrStats[] = [];
+  console.log("Extracting stats from pulls - this may take a while");
+  for (let i = 0; i < pullsFromLastYear.length; i++) {
+    let pull = pullsFromLastYear[i];
+    if (new Date(pull.created_at) > cutoffDate && pull.merged_at) {
+      pullStats.push(await extractPrStats(pull, pullsFromLastYear));
+    }
+    if (i % 10 === 0) {
+      process.stdout.write(".");
+    }
+  }
+
+  console.log("\nDone extracting stats, formatting results");
+
+  let statBuckets: { [key: number]: PrStats[] } = {};
+  let bucketEnd = new Date();
+  bucketEnd.setUTCHours(23, 59, 59, 999);
+  pullStats.forEach((pullStat) => {
+    let bucketStart = getMetricBucketStartDate(pullStat, bucketEnd);
+    if (bucketStart in statBuckets) {
+      statBuckets[bucketStart].push(pullStat);
+    } else {
+      statBuckets[bucketStart] = [pullStat];
+    }
+  });
+  await reportMetrics(statBuckets);
+}
+
+gatherMetrics();
+
+export {};

Review comment:
       I'm not familiar with this self executing export pattern. This pattern could make it difficult to debug when an import causes a side-effect. I think it's better to call `gatherMetrics` from the running class.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819006990



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {

Review comment:
       Actually, scratch that - it is specifically looking for R: @, not just @. I'll keep it but fix the condition




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [beam] damccorm commented on a change in pull request #16985: [BEAM-13925] Add ability to get metrics on pr-bot performance

Posted by GitBox <gi...@apache.org>.
damccorm commented on a change in pull request #16985:
URL: https://github.com/apache/beam/pull/16985#discussion_r819005431



##########
File path: scripts/ci/pr-bot/gatherMetrics.ts
##########
@@ -0,0 +1,527 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const fs = require("fs");
+const github = require("./shared/githubUtils");
+const {
+  REPO_OWNER,
+  REPO,
+  PATH_TO_METRICS_CSV,
+  BOT_NAME,
+} = require("./shared/constants");
+
+interface PrStats {
+  firstTimeContribution: boolean;
+  timeToFirstReview: number;
+  timeFromCreationToCompletion: number;
+  timeFromReviewersMentionedToCompletion: { [key: string]: number };
+  mergedDate: Date;
+}
+
+interface AggregatedMetrics {
+  prsCompleted: number;
+  prsCompletedByNewContributors: number;
+  averageTimeToFirstReview: number;
+  averageTimeToNewContributorFirstReview: number;
+  averageTimeCreationToCompletion: number;
+  numUsersPerformingReviews: number;
+  numCommittersPerformingReviews: number;
+  numNonCommittersPerformingReviews: number;
+  giniIndexCommittersPerformingReviews: number;
+  averageTimeFromCommitterAssignmentToPrMerge: number;
+}
+
+async function getCompletedPullsFromLastYear(): Promise<any[]> {
+  const cutoffDate = new Date(
+    new Date().setFullYear(new Date().getFullYear() - 1)
+  );
+  console.log(`Getting PRs newer than ${cutoffDate}`);
+  const githubClient = github.getGitHubClient();
+  let result = await githubClient.rest.pulls.list({
+    owner: REPO_OWNER,
+    repo: REPO,
+    state: "closed",
+    per_page: 100, // max allowed
+  });
+  let page = 2;
+  let retries = 0;
+  let pulls = result.data;
+  while (
+    result.data.length > 0 &&
+    new Date(result.data[result.data.length - 1].created_at) > cutoffDate
+  ) {
+    if (retries === 0) {
+      console.log(`Getting PRs, page: ${page}`);
+      console.log(
+        `Current oldest PR = ${new Date(
+          result.data[result.data.length - 1].created_at
+        )}`
+      );
+    }
+    try {
+      result = await githubClient.rest.pulls.list({
+        owner: REPO_OWNER,
+        repo: REPO,
+        state: "closed",
+        per_page: 100, // max allowed
+        page: page,
+      });
+      pulls = pulls.concat(result.data);
+      page += 1;
+      retries = 0;
+    } catch (err) {
+      if (retries >= 3) {
+        throw err;
+      }
+      retries += 1;
+    }
+  }
+  console.log("Got all PRs, moving to the processing stage");
+  return pulls;
+}
+
+// Rather than check the whole repo history (expensive),
+// we'll just look at the last year's worth of contributions to check if they're a first time contributor.
+// If they contributed > 1 year ago, their experience is probably similar to a first time contributor anyways.
+function checkIfFirstTimeContributor(
+  pull: any,
+  pullsFromLastYear: any[]
+): boolean {
+  for (const pullFromLastYear of pullsFromLastYear) {
+    if (
+      pullFromLastYear.created_at < pull.created_at &&
+      pullFromLastYear.user.login === pull.user.login
+    ) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+// Get time between pr creation and the first comment, approval, or merge that isn't done by:
+// (a) the author
+// (b) automated tooling
+function getTimeToFirstReview(
+  pull: any,
+  comments: any[],
+  reviews: any[],
+  creationDate: Date,
+  mergedDate: Date
+): number {
+  let timeToFirstReview = mergedDate.getTime() - creationDate.getTime();
+  let i = 0;
+  while (i < reviews.length && reviews[i].user.login === pull.user.login) {
+    i++;
+  }
+  if (i < reviews.length) {
+    const firstReviewDate = new Date(reviews[i].submitted_at);
+    timeToFirstReview = Math.min(
+      timeToFirstReview,
+      firstReviewDate.getTime() - creationDate.getTime()
+    );
+  }
+  for (const comment of comments) {
+    if (
+      comment.user.login != pull.user.login &&
+      comment.user.login != BOT_NAME
+    ) {
+      let commentTime = new Date(comment.created_at);
+      timeToFirstReview = Math.min(
+        timeToFirstReview,
+        commentTime.getTime() - creationDate.getTime()
+      );
+    }
+  }
+  return timeToFirstReview;
+}
+
+// Takes a R: @reviewer comment and extracts all reviewers tagged
+// Returns an empty list if no reviewer can be extracted
+function extractReviewersTaggedFromCommentBody(body: string): string[] {
+  if (!body) {
+    return [];
+  }
+  body = body.toLowerCase();
+  if (body.indexOf("r: @") < -1) {

Review comment:
       That's true - the whole if statement was actually just useless - we take care of it with our while condition below.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org