id: github-pr-review-latency-digest
namespace: company.team
description: |
Weekly review-latency digest for one GitHub repository. For the pull requests merged in the window it measures
time to first review and time to merge (p50 and p90, overall and per label) and compares them with last week.
Open pull requests still waiting for a first review past the SLA get one reminder comment each, and the digest
goes to Discord. Repository-level and per-label numbers only: nothing is broken down per person.
labels:
team: platform
purpose: review-latency
inputs:
- id: repository
type: STRING
defaults: kestra-io/blueprints
description: Repository to measure, as owner/name.
- id: lookback_days
type: INT
defaults: 7
description: Pull requests merged in the last N days form this run's cohort. 1 to 90.
- id: review_sla_hours
type: INT
defaults: 48
description: An open, non-draft pull request with no review after this many
hours is overdue.
- id: post_comments
type: BOOL
defaults: false
description: Post one reminder comment on each overdue pull request. Off by
default, so a first run is read-only.
- id: max_comments
type: INT
defaults: 10
description: At most this many reminder comments per run, oldest first, so a
large backlog is not commented in one go. 1 to 50.
checks:
- when: "{{ {'r': inputs.repository} | jq('.r |
test(\"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$\")') | first }}"
message: repository must be owner/name, for example kestra-io/blueprints.
style: ERROR
behavior: BLOCK_EXECUTION
- when: "{{ inputs.lookback_days >= 1 and inputs.lookback_days <= 90 }}"
message: lookback_days must be between 1 and 90.
style: ERROR
behavior: BLOCK_EXECUTION
- when: "{{ inputs.review_sla_hours >= 1 and inputs.max_comments >= 1 and
inputs.max_comments <= 50 }}"
message: review_sla_hours must be at least 1 and max_comments between 1 and 50.
style: ERROR
behavior: BLOCK_EXECUTION
concurrency:
limit: 1
behavior: QUEUE
triggers:
- id: weekly
type: io.kestra.plugin.core.trigger.Schedule
description: Monday 08:00 UTC. Enable it once a manual run looks right.
cron: "0 8 * * MON"
timezone: UTC
disabled: true
tasks:
- id: context
type: io.kestra.plugin.core.output.OutputValues
description: KV keys for this repository. One stats key per week, so a re-run in
the same week still compares with last week, and one key for the pull
requests already nudged.
values:
since: "{{ now() | dateAdd(0 - inputs.lookback_days, 'DAYS') |
date('yyyy-MM-dd', timeZone='UTC') }}"
stats_key: "pr_review_latency_{{ inputs.repository | replace({'/': '-'}) |
slugify }}_{{ now() | date(\"YYYY-'w'ww\", timeZone='UTC') }}"
last_week_key: "pr_review_latency_{{ inputs.repository | replace({'/': '-'}) |
slugify }}_{{ now() | dateAdd(-7, 'DAYS') | date(\"YYYY-'w'ww\",
timeZone='UTC') }}"
nudged_key: "pr_review_latency_{{ inputs.repository | replace({'/': '-'}) |
slugify }}_nudged"
- id: merged_prs
type: io.kestra.plugin.github.pulls.Search
description: The cohort. For a merged pull request `closed_at` is the merge time.
oauthToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ inputs.repository }}"
query: "is:merged merged:>={{ outputs.context.values.since }}"
fetchType: FETCH
- id: waiting_prs
type: io.kestra.plugin.github.pulls.Search
description: Open, non-draft pull requests that have no review yet.
oauthToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ inputs.repository }}"
query: "is:open draft:false review:none"
fetchType: FETCH
- id: first_reviews
type: io.kestra.plugin.core.flow.Loop
description: |
One call to the reviews endpoint per merged pull request, eight at a time. The first review is the earliest
submitted review (approve, request changes or comment) by someone other than the author and not by a bot.
Reviews come back oldest first, so the first page is enough.
values: "{{ outputs.merged_prs.rows | jq('[.[] | {number, owner}]') | first |
toJson }}"
concurrencyLimit: 8
tasks:
- id: list_reviews
type: io.kestra.plugin.core.http.Request
uri: "https://api.github.com/repos/{{ inputs.repository }}/pulls/{{
fromJson(item.value).number }}/reviews?per_page=100"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: application/vnd.github+json
X-GitHub-Api-Version: "2022-11-28"
retry:
type: exponential
interval: PT2S
maxInterval: PT30S
maxAttempts: 3
outputs:
- id: number
type: INT
value: "{{ fromJson(item.value).number }}"
- id: first_review_at
type: STRING
value: "{{ outputs.list_reviews.body | jq('[.[] | select(.user.login != \"' ~
fromJson(item.value).owner ~ '\" and .user.type != \"Bot\" and .state
!= \"PENDING\") | .submitted_at] | min // \"\"') | first }}"
- id: latency_stats
type: io.kestra.plugin.jdbc.duckdb.Queries
description: |
Percentiles in DuckDB. A review submitted after the merge does not count as a first review. Durations are
differences of epochs: subtracting two TIMESTAMPTZ values gives a calendar interval in the session time zone,
which is an hour off across a daylight-saving change. Results, in order: the cohort summary, the busiest labels,
and the overdue pull requests (oldest first).
timeZoneId: UTC
inputFiles:
merged.json: "{{ outputs.merged_prs.rows | toJson }}"
reviews.json: "{{ (outputs.first_reviews.outputs ?? []) | jq('[.[].outputs]') |
first | toJson }}"
waiting.json: "{{ outputs.waiting_prs.rows | toJson }}"
fetchType: FETCH
sql: |
CREATE MACRO dur(h) AS CASE WHEN h IS NULL THEN 'n/a'
WHEN h < 48 THEN printf('%.1f h', h)
ELSE printf('%.1f d', h / 24) END;
CREATE TABLE merged AS
SELECT m.number,
coalesce(m.labels, []) AS labels,
(epoch(m.closed_at::TIMESTAMPTZ) - epoch(m.created_at::TIMESTAMPTZ)) / 3600 AS merge_h,
CASE WHEN NULLIF(r.first_review_at, '')::TIMESTAMPTZ <= m.closed_at::TIMESTAMPTZ
THEN (epoch(NULLIF(r.first_review_at, '')::TIMESTAMPTZ) - epoch(m.created_at::TIMESTAMPTZ)) / 3600 END AS first_review_h
FROM read_json('{{ workingDir }}/merged.json', format = 'array',
columns = {number: 'INTEGER', labels: 'VARCHAR[]', created_at: 'VARCHAR', closed_at: 'VARCHAR'}) m
LEFT JOIN read_json('{{ workingDir }}/reviews.json', format = 'array',
columns = {number: 'INTEGER', first_review_at: 'VARCHAR'}) r USING (number);
SELECT merged, reviewed, merged - reviewed AS merged_without_review,
round(fr50, 1) AS first_review_p50_h, round(fr90, 1) AS first_review_p90_h,
round(m50, 1) AS merge_p50_h, round(m90, 1) AS merge_p90_h,
dur(fr50) AS first_review_p50, dur(fr90) AS first_review_p90,
dur(m50) AS merge_p50, dur(m90) AS merge_p90
FROM (SELECT count(*) AS merged, count(first_review_h) AS reviewed,
quantile_cont(first_review_h, 0.5) AS fr50, quantile_cont(first_review_h, 0.9) AS fr90,
quantile_cont(merge_h, 0.5) AS m50, quantile_cont(merge_h, 0.9) AS m90
FROM merged);
SELECT coalesce(label, '(no label)') AS label, count(*) AS merged,
dur(median(first_review_h)) AS first_review_p50, dur(median(merge_h)) AS merge_p50
FROM (SELECT unnest(CASE WHEN len(labels) = 0 THEN [NULL::VARCHAR] ELSE labels END) AS label,
merge_h, first_review_h
FROM merged)
GROUP BY 1
ORDER BY merged DESC, label
LIMIT 5;
SELECT number, title, url, waiting_h, dur(waiting_h) AS waiting
FROM (SELECT number, title, url, (epoch(now()) - epoch(created_at::TIMESTAMPTZ)) / 3600 AS waiting_h
FROM read_json('{{ workingDir }}/waiting.json', format = 'array',
columns = {number: 'INTEGER', title: 'VARCHAR', url: 'VARCHAR', created_at: 'VARCHAR'}))
WHERE waiting_h >= {{ inputs.review_sla_hours }}
ORDER BY waiting_h DESC, number;
- id: plan
type: io.kestra.plugin.core.output.OutputValues
description: |
Which overdue pull requests get a comment this run: the oldest ones not already in the nudged list, capped at
`max_comments`. The nudged list kept in KV is the previous list minus pull requests that are no longer waiting
(reviewed, merged, closed or back to draft), plus the ones commented now.
values:
summary: "{{ outputs.latency_stats.outputs[0].rows[0] | toJson }}"
labels: "{{ outputs.latency_stats.outputs[1].rows | toJson }}"
overdue: "{{ outputs.latency_stats.outputs[2].rows | toJson }}"
last_week: "{{ (kv(outputs.context.values.last_week_key, errorOnMissing=false)
?? {}) | toJson }}"
to_nudge: >-
{{ {'o': outputs.latency_stats.outputs[2].rows, 'p':
kv(outputs.context.values.nudged_key, errorOnMissing=false) ?? []}
| jq('. as $d | [$d.o[] | select(.number as $n | [$d.p[] | select(. == $n)] | length == 0)] | .[:' ~ inputs.max_comments ~ ']')
| first | toJson }}
still_nudged: >-
{{ {'w': outputs.waiting_prs.rows | jq('[.[].number]') | first, 'p':
kv(outputs.context.values.nudged_key, errorOnMissing=false) ?? []}
| jq('. as $d | [$d.p[] | select(. as $n | [$d.w[] | select(. == $n)] | length > 0)]')
| first | toJson }}
- id: nudge
type: io.kestra.plugin.core.flow.If
description: The flow acts on the result. With `post_comments` off it only
reports what it would have done.
condition: "{{ fromJson(outputs.plan.values.to_nudge) | length > 0 }}"
then:
- id: comments_on
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.post_comments }}"
then:
- id: comment_each
type: io.kestra.plugin.core.flow.Loop
values: "{{ outputs.plan.values.to_nudge }}"
concurrencyLimit: 1
tasks:
- id: comment
type: io.kestra.plugin.github.issues.Comment
oauthToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ inputs.repository }}"
issueNumber: "{{ fromJson(item.value).number }}"
body: |
<!-- kestra:pr-review-latency-nudge -->
This pull request has been open for {{ fromJson(item.value).waiting }} without a review. The review target for this repository is {{ inputs.review_sla_hours }} h.
It is listed in this week's review-latency digest so a maintainer can pick it up. If it is not ready for review yet, converting it to a draft takes it off the list.
_Posted once per pull request by the Kestra flow `{{ flow.namespace }}.{{ flow.id }}`._
- id: remember_nudged
type: io.kestra.plugin.core.kv.Set
description: Written only after every comment was posted, so a failed comment is
retried next run.
key: "{{ outputs.context.values.nudged_key }}"
kvType: JSON
ttl: P90D
value: "{{ {'kept': fromJson(outputs.plan.values.still_nudged), 'new':
fromJson(outputs.plan.values.to_nudge)} | jq('.kept +
[.new[].number] | unique') | first | toJson }}"
else:
- id: dry_run
type: io.kestra.plugin.core.log.Log
message: "post_comments is off: would comment on {{
fromJson(outputs.plan.values.to_nudge) | jq('[.[] | \"#\" +
(.number | tostring)] | join(\", \")') | first }}."
- id: digest
type: io.kestra.plugin.core.output.OutputValues
description: The digest text, also used as the Discord embed.
values:
text: |
{%- set s = fromJson(outputs.plan.values.summary) -%}
{%- set lw = fromJson(outputs.plan.values.last_week) -%}
{%- set overdue = fromJson(outputs.plan.values.overdue) -%}
{%- set nudge = fromJson(outputs.plan.values.to_nudge) -%}
**Merged since {{ outputs.context.values.since }}:** {{ s.merged }} pull requests, {{ s.merged_without_review }} merged without a review.
**Time to first review:** p50 {{ s.first_review_p50 }}, p90 {{ s.first_review_p90 }}{{ lw.summary is defined ? ' (last week p50 ' ~ lw.summary.first_review_p50 ~ ')' : '' }}
**Time to merge:** p50 {{ s.merge_p50 }}, p90 {{ s.merge_p90 }}{{ lw.summary is defined ? ' (last week p50 ' ~ lw.summary.merge_p50 ~ ')' : '' }}
**Waiting for a first review:** {{ outputs.waiting_prs.size }} open, {{ overdue | length }} past the {{ inputs.review_sla_hours }} h target{{ lw.overdue is defined ? ' (last week ' ~ lw.overdue ~ ')' : '' }}.
{%- if nudge | length > 0 %}
{{ inputs.post_comments ? 'Reminder comments posted this run: ' : 'Comments are off, reminders that would be posted: ' }}{{ nudge | jq('[.[] | "#" + (.number | tostring)] | join(", ")') | first }}.
{%- endif %}
{%- if fromJson(outputs.plan.values.labels) | length > 0 %}
**By label** (merged, p50 first review, p50 merge)
{%- for l in fromJson(outputs.plan.values.labels) %}
- `{{ l.label }}`: {{ l.merged }}, {{ l.first_review_p50 }}, {{ l.merge_p50 }}
{%- endfor %}
{%- endif %}
{%- if overdue | length > 0 %}
**Waiting longest**
{%- for p in overdue %}{% if loop.index < 5 %}
- [#{{ p.number }}]({{ p.url }}) {{ p.title | abbreviate(70) }}, {{ p.waiting }}
{%- endif %}{% endfor %}
{%- endif %}
- id: notify
type: io.kestra.plugin.discord.DiscordIncomingWebhook
url: "{{ secret('DISCORD_WEBHOOK_URL') }}"
payload: |
{{ {
'username': 'Kestra',
'embeds': [{
'title': 'PR review latency: ' ~ inputs.repository,
'url': 'https://github.com/' ~ inputs.repository ~ '/pulls',
'description': outputs.digest.values.text | abbreviate(4000),
'color': 5793266
}]
} | toJson }}
- id: save_week
type: io.kestra.plugin.core.kv.Set
description: Saved after the digest went out, for next week's comparison. Kept
five weeks.
key: "{{ outputs.context.values.stats_key }}"
kvType: JSON
ttl: P35D
value: "{{ {'execution_id': execution.id, 'since': outputs.context.values.since,
'summary': fromJson(outputs.plan.values.summary), 'waiting':
outputs.waiting_prs.size, 'overdue': fromJson(outputs.plan.values.overdue)
| length} | toJson }}"
errors:
- id: alert_failure
type: io.kestra.plugin.discord.DiscordIncomingWebhook
url: "{{ secret('DISCORD_WEBHOOK_URL') }}"
payload: |
{{ {
'username': 'Kestra',
'content': 'PR review-latency digest for ' ~ inputs.repository ~ ' failed in execution ' ~ execution.id ~ ': ' ~ (((errorLogs() | length) > 0 ? errorLogs()[0].message : 'see the execution logs') | abbreviate(1500))
} | toJson }}
finally:
- id: purge_files
type: io.kestra.plugin.core.storage.PurgeCurrentExecutionFiles
description: The DuckDB input files hold pull request titles; nothing needs to
stay in internal storage once the digest is sent.
outputs:
- id: summary
type: JSON
description: Merged count, pull requests merged without a review, and p50 and
p90 hours to first review and to merge.
value: "{{ fromJson(outputs.plan.values.summary ?? '{}') }}"
- id: overdue
type: JSON
description: Open, non-draft pull requests with no review past the target, oldest first.
value: "{{ fromJson(outputs.plan.values.overdue ?? '[]') }}"