Skip to main content

orch/engine/ci/
mod.rs

1//! CI timers, required checks and red CI context
2
3pub mod bootstrap;
4pub mod gate;
5
6use crate::github::http::GhHttp;
7use crate::github::types::is_own_check;
8use crate::github::types::{GitHubCheckRun, RequiredStatusCheck};
9use crate::security;
10use crate::store::TaskStore;
11use crate::store::store_increment;
12use std::collections::HashSet;
13use std::fmt::Write as _;
14use std::sync::Arc;
15
16/// Record that CI was checked for this task, updating the timestamp in KV store.
17/// Maximum number of CI failure or CI timeout events in `auto_merge_pr` before
18/// the task is blocked for human intervention instead of re-entering NeedsReview.
19pub(crate) const MAX_CI_MERGE_FAILURES: u64 = 3;
20
21/// Merge-time CI-failure block. The recovery sweep only acts on this stage
22pub(crate) const CI_FAILURE_AUTO_MERGE_STAGE: &str = "during auto-merge";
23
24/// Pre-review CI-failure block. A person unblocks these, recovery must not merge them
25pub(crate) const CI_FAILURE_BEFORE_REVIEW_STAGE: &str = "before review";
26
27/// Shared by the review gate and auto-merge so the recovery sweep can tell them apart
28pub(crate) fn ci_failure_limit_reason(stage: &str) -> String {
29    format!("CI failure limit ({MAX_CI_MERGE_FAILURES}) reached {stage}")
30}
31
32pub(super) async fn record_ci_check(
33    store: &Arc<TaskStore>,
34    repo: &str,
35    task_id: &str,
36) -> anyhow::Result<()> {
37    let key = ci_check_ts_key(repo, task_id);
38    let now = chrono::Utc::now().to_rfc3339();
39    store.kv_set(&key, &now).await
40}
41
42pub(super) fn ci_check_ts_key(repo: &str, task_id: &str) -> String {
43    format!("ci_check_ts:{repo}#{task_id}")
44}
45
46/// Prefix shared by the pending timers of every head of one task
47pub(super) fn ci_pending_since_prefix(repo: &str, task_id: &str) -> String {
48    format!("ci_pending_since:{repo}#{task_id}#")
49}
50
51/// The head sha in the key means a new head starts a new pending window
52pub(super) fn ci_pending_since_key(repo: &str, task_id: &str, head_sha: &str) -> String {
53    format!("{}{head_sha}", ci_pending_since_prefix(repo, task_id))
54}
55
56/// Prefix shared by the counted-failure keys of every head of one task
57fn ci_failure_sha_prefix(repo: &str, task_id: &str) -> String {
58    format!("ci_failure_sha:{repo}#{task_id}#")
59}
60
61pub(super) fn ci_failure_sha_key(repo: &str, task_id: &str, head_sha: &str) -> String {
62    format!("{}{head_sha}", ci_failure_sha_prefix(repo, task_id))
63}
64
65/// Increment `ci_merge_failures` once per head SHA. `None` when this SHA was already counted
66pub(crate) async fn count_ci_failure_for_head(
67    store: &Arc<TaskStore>,
68    repo: &str,
69    task_id: &str,
70    head_sha: &str,
71) -> anyhow::Result<Option<u64>> {
72    let key = (!head_sha.is_empty()).then(|| ci_failure_sha_key(repo, task_id, head_sha));
73    if let Some(ref key) = key
74        && store.kv_increment(key).await? > 1
75    {
76        return Ok(None);
77    }
78    match store_increment(&Some(Arc::clone(store)), repo, task_id, "ci_merge_failures").await {
79        Ok(n) => Ok(Some(n)),
80        Err(e) => {
81            if let Some(ref key) = key
82                && let Err(del) = store.kv_delete(key).await
83            {
84                tracing::warn!(
85                    task_id,
86                    err = %del,
87                    "failed to roll back ci_failure_sha after increment error"
88                );
89            }
90            Err(e)
91        }
92    }
93}
94
95/// Return how long CI has been continuously observed as `pending` for this
96/// task, persisting the first-seen timestamp in the KV store.
97///
98/// `auto_merge_pr` runs as many short-lived invocations rather than one long
99/// blocking call — `is_ci_check_in_cooldown` returns early well before
100/// `max_wait` elapses, and the next sync tick spawns a fresh invocation with
101/// its own local `Instant`. A local `start.elapsed()` therefore never
102/// accumulates past a few seconds, so the pending-timeout escalation can
103/// never fire. Persisting "first seen pending" here lets elapsed time
104/// accumulate across those invocations the same way `ci_check_ts` already
105/// does for the check cooldown.
106pub(super) async fn ci_pending_elapsed(
107    store: &Arc<TaskStore>,
108    repo: &str,
109    task_id: &str,
110    head_sha: &str,
111) -> anyhow::Result<chrono::Duration> {
112    let key = ci_pending_since_key(repo, task_id, head_sha);
113    let now = chrono::Utc::now();
114    // `auto_merge_pr` can run as two overlapping invocations for the same task
115    // (the review-agent's direct approval call in review.rs races the periodic
116    // review_open_prs sweep, which is not guarded against that call site). A
117    // plain "read, then write-if-absent" has a TOCTOU window where both
118    // invocations observe an absent key and each writes its own "now",
119    // silently discarding whichever wrote first and resetting the elapsed
120    // clock. `kv_insert_if_absent` performs the check-and-set in one SQL
121    // statement so only the first writer's timestamp survives.
122    let stored = store.kv_insert_if_absent(&key, &now.to_rfc3339()).await?;
123    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&stored) {
124        Ok(now.signed_duration_since(dt.with_timezone(&chrono::Utc)))
125    } else {
126        tracing::warn!(
127            task_id,
128            stored,
129            "ci_pending_since value unparseable — resetting"
130        );
131        store.kv_set(&key, &now.to_rfc3339()).await?;
132        Ok(chrono::Duration::zero())
133    }
134}
135
136/// Clear the persisted pending-since timestamp once CI leaves the pending
137/// state (success, failure, or after a timeout escalation fires) so the next
138/// pending streak starts fresh.
139///
140/// `reason` identifies which branch triggered the clear (e.g. "ci_success",
141/// "ci_failure", "pending_timeout_escalation") and is logged alongside the
142/// value being cleared, so a future occurrence of the elapsed time silently
143/// resetting (see #3609) is diagnosable from logs alone instead of requiring
144/// another multi-day live reproduction.
145pub(super) async fn clear_ci_pending_since(
146    store: &Arc<TaskStore>,
147    repo: &str,
148    task_id: &str,
149    reason: &str,
150) -> anyhow::Result<()> {
151    for (key, prior) in store
152        .kv_list_prefix(&ci_pending_since_prefix(repo, task_id))
153        .await?
154    {
155        tracing::debug!(task_id, reason, prior_since = %prior, "clearing ci_pending_since");
156        store.kv_delete(&key).await?;
157    }
158    Ok(())
159}
160
161/// Delete the CI timers of tasks that finished, and the bare-id keys older versions wrote
162pub(crate) async fn sweep_ci_timer_keys(
163    store: &Arc<TaskStore>,
164    repo: &str,
165    finished_task_ids: &[String],
166) -> anyhow::Result<()> {
167    let finished: HashSet<&str> = finished_task_ids.iter().map(String::as_str).collect();
168    let repo_marker = format!("{repo}#");
169    for prefix in [
170        "ci_check_ts:",
171        "ci_pending_since:",
172        "review_ci_wait_since:",
173        "ci_failure_sha:",
174        "ci_bootstrap_wait_since:",
175        "ci_bootstrap_no_checks_comment:",
176        "ci_bootstrap_never_run_comment:",
177    ] {
178        for (key, _) in store.kv_list_prefix(prefix).await? {
179            let rest = &key[prefix.len()..];
180            let stale = match rest.strip_prefix(repo_marker.as_str()) {
181                // Pending keys carry a trailing `#{head_sha}`
182                Some(tail) => finished.contains(tail.split('#').next().unwrap_or(tail)),
183                None => !rest.contains('#'),
184            };
185            if stale {
186                store.kv_delete(&key).await?;
187            }
188        }
189    }
190    Ok(())
191}
192
193pub(crate) fn required_checks_state(
194    required_contexts: &[RequiredStatusCheck],
195    check_runs: &[GitHubCheckRun],
196    statuses: &[(String, String)],
197) -> (String, u64, u64, u64, u64) {
198    if required_contexts.is_empty() {
199        return ("success".to_string(), 0, 0, 0, 0);
200    }
201
202    let mut passing = 0u64;
203    let mut failing = 0u64;
204    let mut pending = 0u64;
205
206    for required in required_contexts {
207        let mut matched = false;
208
209        if let Some(run) = check_runs
210            .iter()
211            .find(|run| required_check_run_matches(required, run))
212        {
213            matched = true;
214            if !run.is_finished() {
215                pending += 1;
216            } else if run.is_passed() {
217                passing += 1;
218            } else {
219                failing += 1;
220            }
221        } else {
222            for (name, state) in statuses {
223                if !required_commit_status_matches(required, name) {
224                    continue;
225                }
226                matched = true;
227                match state.as_str() {
228                    "success" | "neutral" | "skipped" => passing += 1,
229                    "failure" | "error" => failing += 1,
230                    _ => pending += 1,
231                }
232                break;
233            }
234        }
235
236        if !matched {
237            pending += 1;
238        }
239    }
240
241    let total = required_contexts.len() as u64;
242    let state = if failing > 0 {
243        "failure".to_string()
244    } else if pending > 0 {
245        "pending".to_string()
246    } else {
247        "success".to_string()
248    };
249
250    (state, total, passing, failing, pending)
251}
252
253pub(crate) fn required_check_run_matches(
254    required: &RequiredStatusCheck,
255    run: &GitHubCheckRun,
256) -> bool {
257    if run.name != required.context {
258        return false;
259    }
260    match required.integration_id {
261        None => true,
262        Some(id) => run.app.as_ref().is_some_and(|app| app.id == id),
263    }
264}
265
266pub(crate) fn required_commit_status_matches(
267    required: &RequiredStatusCheck,
268    context: &str,
269) -> bool {
270    required.integration_id.is_none() && required.context == context
271}
272
273const CI_LOG_TAIL_LINES: usize = 80;
274
275const CI_CONTEXT_MAX_CHARS: usize = 8000;
276
277/// The `pr_review_context` for a task routed back on red CI (#4121), empty `failed` means all
278pub(crate) async fn red_ci_context(
279    gh: &GhHttp,
280    repo: &str,
281    pr_number: u64,
282    sha: &str,
283    failed: &[String],
284) -> String {
285    let mut sections: Vec<(String, String)> = Vec::new();
286    match gh.get_check_runs(repo, sha).await {
287        Ok(runs) => {
288            let failed_runs = runs.iter().filter(|r| {
289                matches!(r.conclusion.as_deref(), Some("failure" | "timed_out"))
290                    && (failed.is_empty() || failed.contains(&r.name))
291            });
292            for run in failed_runs {
293                sections.push((run.name.clone(), failure_text(gh, repo, run).await));
294            }
295        }
296        Err(e) => {
297            tracing::debug!(err = %e, "failed to fetch check runs for the CI failure context");
298        }
299    }
300    for name in failed {
301        if !sections.iter().any(|(n, _)| n == name) {
302            sections.push((name.clone(), String::new()));
303        }
304    }
305    format_red_ci_context(pr_number, sha, &sections)
306}
307
308/// Annotations of a failed check run, or the tail of its job log when it has none
309async fn failure_text(gh: &GhHttp, repo: &str, run: &GitHubCheckRun) -> String {
310    match gh.get_check_run_annotations(repo, run.id).await {
311        Ok(annotations) => {
312            let lines: Vec<String> = annotations
313                .iter()
314                .filter(|a| a.annotation_level.as_deref() != Some("notice"))
315                .map(|a| {
316                    let place = match (&a.path, a.start_line) {
317                        (Some(path), Some(line)) => format!("{path}:{line}: "),
318                        (Some(path), None) => format!("{path}: "),
319                        _ => String::new(),
320                    };
321                    let title = a.title.as_deref().unwrap_or("");
322                    let message = a.message.as_deref().unwrap_or("");
323                    format!("{place}{title} {message}").trim().to_string()
324                })
325                .filter(|l| !l.is_empty())
326                .collect();
327            if !lines.is_empty() {
328                return lines.join("\n");
329            }
330        }
331        Err(e) => {
332            tracing::debug!(check_run_id = run.id, err = %e, "failed to fetch check run annotations");
333        }
334    }
335    gh.get_job_log_tail(repo, run.id, CI_LOG_TAIL_LINES)
336        .await
337        .unwrap_or_default()
338}
339
340pub(crate) fn format_red_ci_context(
341    pr_number: u64,
342    sha: &str,
343    sections: &[(String, String)],
344) -> String {
345    let names = sections
346        .iter()
347        .map(|(n, _)| n.as_str())
348        .collect::<Vec<_>>()
349        .join(", ");
350    let mut out = format!(
351        "CI failed on PR #{pr_number} at head {sha}. Failed checks: {names}.\n\
352         Run each failing check locally and fix it. Do not report done until it passes.\n"
353    );
354    for (name, text) in sections {
355        let text = text.trim();
356        let text = if text.is_empty() {
357            "No failure text was available. Read the log of this check on the PR."
358        } else {
359            text
360        };
361        let _ = write!(out, "\n### {name}\n```\n{text}\n```\n");
362    }
363    let mut out = security::redact(&out);
364    if out.chars().count() > CI_CONTEXT_MAX_CHARS {
365        out = out.chars().take(CI_CONTEXT_MAX_CHARS).collect();
366        out.push_str("\n[truncated]");
367    }
368    out
369}
370
371/// Counts failed check runs for `sha` that carry a GitHub Actions billing
372/// failure annotation.
373///
374/// When an account has unpaid invoices or has hit a spending limit, GitHub
375/// refuses to start jobs and records the reason ("The job was not started
376/// because recent account payments have failed …") as a check-run annotation.
377/// The CI state still comes back as `"failure"`, which would normally trigger
378/// the agent retry loop — but no code change can fix a billing problem.
379/// This function lets the caller short-circuit that loop and block the task
380/// immediately with a human-readable billing message instead.
381pub(crate) async fn billing_failed_runs(
382    gh: &GhHttp,
383    repo: &str,
384    sha: &str,
385    prefetched: Option<Vec<GitHubCheckRun>>,
386) -> u64 {
387    let check_runs = match prefetched {
388        Some(runs) => runs,
389        None => match gh.get_check_runs(repo, sha).await {
390            Ok(runs) => runs,
391            Err(e) => {
392                tracing::debug!(err = %e, "failed to fetch check runs for billing failure check");
393                return 0;
394            }
395        },
396    };
397
398    let mut count = 0;
399    for run in check_runs
400        .iter()
401        .filter(|r| r.conclusion.as_deref() == Some("failure"))
402    {
403        match gh.get_check_run_annotations(repo, run.id).await {
404            Ok(annotations) => {
405                for annotation in &annotations {
406                    let msg = annotation.message.as_deref().unwrap_or("");
407                    let title = annotation.title.as_deref().unwrap_or("");
408                    if msg.contains("account payments have failed")
409                        || msg.contains("spending limit")
410                        || title.contains("account payments have failed")
411                        || title.contains("spending limit")
412                    {
413                        count += 1;
414                        break;
415                    }
416                }
417            }
418            Err(e) => {
419                tracing::debug!(
420                    check_run_id = run.id,
421                    err = %e,
422                    "failed to fetch check run annotations"
423                );
424            }
425        }
426    }
427
428    count
429}
430
431/// Whether a PR head may merge, given how many commits it is behind its base.
432///
433/// `None` means the comparison could not be read. Only a head that contains the
434/// base tip has run its checks against the code the merge would produce, so an
435/// unreadable comparison holds the merge too (#3780)
436pub(super) fn may_merge_onto_base(behind_by: Option<u64>) -> bool {
437    behind_by == Some(0)
438}
439
440/// True when any check run or commit status has not finished
441pub(super) fn any_check_pending(
442    check_runs: &[GitHubCheckRun],
443    statuses: &[(String, String)],
444) -> bool {
445    check_runs
446        .iter()
447        .any(|run| !is_own_check(&run.name) && !run.is_finished())
448        || statuses.iter().any(|(name, state)| {
449            !is_own_check(name)
450                && !matches!(
451                    state.as_str(),
452                    "success" | "failure" | "error" | "neutral" | "skipped"
453                )
454        })
455}
456
457/// Names of completed checks that failed and are not required
458pub(super) fn failing_optional_check_names(
459    required: &[RequiredStatusCheck],
460    check_runs: &[GitHubCheckRun],
461    statuses: &[(String, String)],
462) -> Vec<String> {
463    let mut names = Vec::new();
464    for run in check_runs {
465        if required.iter().any(|r| required_check_run_matches(r, run)) {
466            continue;
467        }
468        if run.is_finished() && !run.is_passed() {
469            names.push(run.name.clone());
470        }
471    }
472    for (name, state) in statuses {
473        if !matches!(state.as_str(), "failure" | "error") {
474            continue;
475        }
476        if required
477            .iter()
478            .any(|r| required_commit_status_matches(r, name))
479        {
480            continue;
481        }
482        if !names.contains(name) {
483            names.push(name.clone());
484        }
485    }
486    names
487}
488
489/// `has_hooks` is `clean` on a server with pre-receive hooks
490/// `unstable` is ready when required checks passed, and waits while a repo with no required checks still has running CI
491pub(super) fn mergeable_state_ready(
492    state: &str,
493    required: &[RequiredStatusCheck],
494    check_runs: &[GitHubCheckRun],
495    statuses: &[(String, String)],
496) -> bool {
497    match state {
498        "clean" | "has_hooks" => true,
499        "unstable" => {
500            if required.is_empty() {
501                !any_check_pending(check_runs, statuses)
502            } else {
503                required_checks_state(required, check_runs, statuses).0 == "success"
504            }
505        }
506        _ => false,
507    }
508}
509
510/// Check whether all *required* CI checks pass for the given PR.
511///
512/// Returns `Some(true)` when all required contexts report success, `Some(false)` when
513/// at least one required check is failing or pending, and `None` on any API error (so
514/// the caller can fall through to the default escalation path).
515pub(super) async fn required_ci_checks_pass(
516    gh: &GhHttp,
517    repo: &str,
518    pr_number: u64,
519) -> Option<bool> {
520    let pr = match gh.get_pr(repo, pr_number).await {
521        Ok(pr) => pr,
522        Err(e) => {
523            tracing::warn!(pr_number, err = %e, "required_ci_checks_pass: failed to fetch PR");
524            return None;
525        }
526    };
527
528    let head_sha = pr.head.sha.clone();
529    let base_branch = pr.base.ref_.clone();
530
531    let required_contexts = match gh
532        .get_required_status_check_contexts(repo, &base_branch)
533        .await
534    {
535        Ok(ctx) => ctx,
536        Err(e) => {
537            tracing::warn!(
538                pr_number,
539                err = %e,
540                "required_ci_checks_pass: failed to fetch required contexts"
541            );
542            return None;
543        }
544    };
545
546    // No required contexts configured — treat as passing.
547    if required_contexts.is_empty() {
548        return Some(true);
549    }
550
551    let check_runs = match gh.get_check_runs(repo, &head_sha).await {
552        Ok(runs) => runs,
553        Err(e) => {
554            tracing::warn!(
555                pr_number,
556                err = %e,
557                "required_ci_checks_pass: failed to fetch check runs"
558            );
559            return None;
560        }
561    };
562
563    let statuses = match gh.get_commit_status_contexts(repo, &head_sha).await {
564        Ok(s) => s,
565        Err(e) => {
566            tracing::warn!(
567                pr_number,
568                err = %e,
569                "required_ci_checks_pass: failed to fetch commit statuses"
570            );
571            return None;
572        }
573    };
574
575    let (state, ..) = required_checks_state(&required_contexts, &check_runs, &statuses);
576    Some(state == "success")
577}