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