Skip to main content

orch/engine/git/
push_retry.rs

1//! Engine side retry of a push that failed on a GitHub or network error (#4025, #4051), with no agent run
2
3use crate::engine::git::{git_ops, worktree};
4use crate::github::types::parse_pr_number_from_url;
5use crate::store;
6use crate::store::{Task, TaskStore, opt_store_get_task};
7use chrono::Utc;
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11/// The push failure count that blocks the task, the run counts as the first failure
12pub(crate) const MAX_PUSH_FAILURES: u64 = 4;
13
14/// Wait after the first, second and third failure
15const BACKOFF_SECS: [i64; 3] = [60, 5 * 60, 15 * 60];
16
17/// What a retry attempt did
18#[derive(Debug, PartialEq)]
19pub(crate) enum PushRetry {
20    /// The task has no transient push failure to retry
21    NotPending,
22    /// The backoff has not ended
23    Wait,
24    /// The branch reached the remote
25    Pushed,
26    /// The push failed again, a later tick tries it again
27    Failed,
28    /// The last allowed push failed
29    Exhausted(String),
30    /// The push failed for a reason that needs the task agent
31    NeedsAgent(String),
32}
33
34fn retry_key(repo: &str, task_id: &str) -> String {
35    format!("push_retry_at:{repo}#{task_id}")
36}
37
38/// Seconds to wait after the given number of failed pushes
39pub(crate) fn backoff_secs(push_failures: i64) -> i64 {
40    let idx = usize::try_from(push_failures.max(1) - 1)
41        .unwrap_or(0)
42        .min(BACKOFF_SECS.len() - 1);
43    BACKOFF_SECS[idx]
44}
45
46/// A task whose last push failed on a GitHub or network error, including a later commit on an existing PR
47pub(crate) fn is_pending(task: &Task) -> bool {
48    task.push_failures > 0
49        && u64::try_from(task.push_failures).is_ok_and(|n| n < MAX_PUSH_FAILURES)
50        && !task.worktree.trim().is_empty()
51        && !task.branch.trim().is_empty()
52        && task.last_error.contains("push failed")
53        && !task.last_error.contains("push failed and rebase failed:")
54        && git_ops::is_transient_network_error(&task.last_error)
55}
56
57fn push_error_text(err: &str) -> String {
58    if err.starts_with("push failed") {
59        err.to_string()
60    } else {
61        format!("push failed: {err}")
62    }
63}
64
65/// Push the branch of a task that waits on a failed push, once its backoff ended
66pub(crate) async fn retry_pending_push(
67    store: &Arc<TaskStore>,
68    repo: &str,
69    task_id: &str,
70) -> PushRetry {
71    let opt_store = Some(Arc::clone(store));
72    let Some(task) = opt_store_get_task(&opt_store, repo, task_id).await else {
73        return PushRetry::NotPending;
74    };
75    let worktree_path = PathBuf::from(&task.worktree);
76    if !is_pending(&task) || !worktree_path.exists() {
77        return PushRetry::NotPending;
78    }
79
80    let key = retry_key(repo, task_id);
81    let now = Utc::now().timestamp();
82    match store.kv_get(&key).await {
83        Ok(Some(due)) if now >= due.parse().unwrap_or(0) => {}
84        Ok(Some(_)) => return PushRetry::Wait,
85        Ok(None) => {
86            let due = now + backoff_secs(i64::from(task.push_failures));
87            if let Err(e) = store.kv_set(&key, &due.to_string()).await {
88                tracing::warn!(task_id, err = %e, "failed to store the push retry time");
89            }
90            return PushRetry::Wait;
91        }
92        Err(e) => {
93            tracing::warn!(task_id, err = %e, "failed to read the push retry time");
94            return PushRetry::Wait;
95        }
96    }
97
98    let default_branch = worktree::detect_default_branch(&worktree_path).await;
99    tracing::info!(
100        task_id,
101        branch = %task.branch,
102        push_failures = task.push_failures,
103        "retrying the push from the engine"
104    );
105    match git_ops::push_branch(&worktree_path, &task.branch, &default_branch).await {
106        Ok(true) => {
107            log_push(store, repo, task_id, &task, "ok", None).await;
108            store.kv_delete(&key).await.ok();
109            store::store_set(
110                &opt_store,
111                repo,
112                task_id,
113                &[
114                    ("last_error", serde_json::json!("")),
115                    ("push_failures", serde_json::json!(0)),
116                ],
117            )
118            .await;
119            if task.pr_number.is_none() {
120                open_pr(store, repo, task_id, &task, &worktree_path, &default_branch).await;
121            }
122            PushRetry::Pushed
123        }
124        Ok(false) => {
125            let err = "push skipped".to_string();
126            log_push(store, repo, task_id, &task, "skipped", Some(&err)).await;
127            store.kv_delete(&key).await.ok();
128            PushRetry::NeedsAgent(err)
129        }
130        Err(e) => {
131            let err = push_error_text(&e.to_string());
132            log_push(store, repo, task_id, &task, "error", Some(&err)).await;
133            store::store_set(
134                &opt_store,
135                repo,
136                task_id,
137                &[("last_error", serde_json::json!(err))],
138            )
139            .await;
140            if !git_ops::is_transient_network_error(&err) {
141                store.kv_delete(&key).await.ok();
142                return PushRetry::NeedsAgent(err);
143            }
144            let failures = store::store_increment(&opt_store, repo, task_id, "push_failures")
145                .await
146                .unwrap_or_else(|_| u64::try_from(task.push_failures).unwrap_or(0) + 1);
147            if failures >= MAX_PUSH_FAILURES {
148                store.kv_delete(&key).await.ok();
149                return PushRetry::Exhausted(err);
150            }
151            let due = Utc::now().timestamp() + backoff_secs(i64::try_from(failures).unwrap_or(1));
152            if let Err(e) = store.kv_set(&key, &due.to_string()).await {
153                tracing::warn!(task_id, err = %e, "failed to store the push retry time");
154            }
155            PushRetry::Failed
156        }
157    }
158}
159
160async fn log_push(
161    store: &Arc<TaskStore>,
162    repo: &str,
163    task_id: &str,
164    task: &Task,
165    status: &str,
166    error: Option<&str>,
167) {
168    store::store_log_activity(
169        &Some(Arc::clone(store)),
170        repo,
171        task_id,
172        "push",
173        None,
174        None,
175        task.agent.as_deref(),
176        task.model.as_deref(),
177        Some(&serde_json::json!({
178            "status": status,
179            "branch": task.branch,
180            "phase": "engine_retry",
181            "error": error,
182        })),
183    )
184    .await;
185}
186
187/// Open the PR the run could not open, the review gate opens it when this fails
188async fn open_pr(
189    store: &Arc<TaskStore>,
190    repo: &str,
191    task_id: &str,
192    task: &Task,
193    worktree_path: &Path,
194    default_branch: &str,
195) {
196    if repo.is_empty() {
197        return;
198    }
199    let opt_store = Some(Arc::clone(store));
200    let created = git_ops::create_pr_if_needed(
201        worktree_path,
202        &task.branch,
203        &task.title,
204        &task.summary,
205        &[],
206        &[],
207        &[],
208        task_id,
209        task.agent.as_deref().unwrap_or_default(),
210        task.model.as_deref(),
211        repo,
212        default_branch,
213    )
214    .await;
215    match created {
216        Ok(url) => match parse_pr_number_from_url(&url) {
217            Ok(pr_number) => {
218                store::store_set(
219                    &opt_store,
220                    repo,
221                    task_id,
222                    &[("pr_number", serde_json::json!(pr_number))],
223                )
224                .await;
225            }
226            Err(e) => {
227                tracing::warn!(task_id, url, err = %e, "pushed, but the PR number is unreadable");
228            }
229        },
230        Err(e) => {
231            tracing::warn!(task_id, err = %e, "pushed, but the PR is not open yet");
232        }
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239    use crate::store::NewTask;
240    use std::fs;
241    #[cfg(unix)]
242    use std::os::unix::fs::PermissionsExt;
243    use std::process::Command;
244
245    const FAILED_PUSH: &str = "push failed: remote: fatal error in commit_refs\n ! [remote rejected] feature -> feature (pre-receive hook declined)";
246
247    /// A clone with one commit ahead on a feature branch, and the bare remote it pushes to
248    struct Fixture {
249        _tmp: tempfile::TempDir,
250        clone: PathBuf,
251        remote: PathBuf,
252    }
253
254    fn git(dir: &Path, args: &[&str]) {
255        let out = Command::new("git")
256            .args(args)
257            .current_dir(dir)
258            .env("GIT_CONFIG_GLOBAL", "/dev/null")
259            .output()
260            .unwrap();
261        assert!(out.status.success(), "git {args:?}: {out:?}");
262    }
263
264    fn fixture() -> Fixture {
265        let tmp = tempfile::tempdir().unwrap();
266        let remote = tmp.path().join("remote.git");
267        let clone = tmp.path().join("clone");
268        fs::create_dir_all(&remote).unwrap();
269        git(&remote, &["init", "--bare", "-b", "main"]);
270        git(tmp.path(), &["clone", remote.to_str().unwrap(), "clone"]);
271        git(&clone, &["config", "user.email", "t@example.com"]);
272        git(&clone, &["config", "user.name", "t"]);
273        git(&clone, &["checkout", "-b", "main"]);
274        fs::write(clone.join("a.txt"), "a").unwrap();
275        git(&clone, &["add", "."]);
276        git(&clone, &["commit", "-m", "base"]);
277        git(&clone, &["push", "-u", "origin", "main"]);
278        git(&clone, &["checkout", "-b", "feature"]);
279        fs::write(clone.join("b.txt"), "b").unwrap();
280        git(&clone, &["add", "."]);
281        git(&clone, &["commit", "-m", "work"]);
282        Fixture {
283            _tmp: tmp,
284            clone,
285            remote,
286        }
287    }
288
289    /// Make the remote fail the way GitHub did during the outage
290    fn break_remote(remote: &Path) {
291        let hook = remote.join("hooks/pre-receive");
292        fs::write(
293            &hook,
294            "#!/bin/sh\necho 'fatal error in commit_refs' >&2\nexit 1\n",
295        )
296        .unwrap();
297        #[cfg(unix)]
298        fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap();
299    }
300
301    async fn pending_task(store: &Arc<TaskStore>, fx: &Fixture, failures: i32) -> String {
302        let id = store
303            .create(&NewTask {
304                title: "Work".to_string(),
305                ..Default::default()
306            })
307            .await
308            .unwrap();
309        store
310            .set_fields(
311                id,
312                &[
313                    ("worktree", serde_json::json!(fx.clone.to_str().unwrap())),
314                    ("branch", serde_json::json!("feature")),
315                    ("last_error", serde_json::json!(FAILED_PUSH)),
316                    ("push_failures", serde_json::json!(failures)),
317                ],
318            )
319            .await
320            .unwrap();
321        format!("internal:{id}")
322    }
323
324    async fn set_pr_number(store: &Arc<TaskStore>, task_id: &str, pr_number: i32) {
325        let store_id = store.resolve_task_id("", task_id).await.unwrap().unwrap();
326        store
327            .set_fields(store_id, &[("pr_number", serde_json::json!(pr_number))])
328            .await
329            .unwrap();
330    }
331
332    /// The first feature commit is already on the remote, as it is for an open PR
333    fn extra_unpushed_commit(fx: &Fixture) {
334        git(&fx.clone, &["push", "-u", "origin", "feature"]);
335        fs::write(fx.clone.join("c.txt"), "c").unwrap();
336        git(&fx.clone, &["add", "."]);
337        git(&fx.clone, &["commit", "-m", "more"]);
338    }
339
340    fn remote_log(fx: &Fixture) -> String {
341        let out = Command::new("git")
342            .args(["log", "feature", "--oneline"])
343            .current_dir(&fx.remote)
344            .env("GIT_CONFIG_GLOBAL", "/dev/null")
345            .output()
346            .unwrap();
347        String::from_utf8_lossy(&out.stdout).into_owned()
348    }
349
350    async fn stored(store: &Arc<TaskStore>, task_id: &str) -> Task {
351        opt_store_get_task(&Some(Arc::clone(store)), "", task_id)
352            .await
353            .unwrap()
354    }
355
356    #[test]
357    fn backoff_grows_and_caps() {
358        assert_eq!(backoff_secs(0), 60);
359        assert_eq!(backoff_secs(1), 60);
360        assert_eq!(backoff_secs(2), 300);
361        assert_eq!(backoff_secs(3), 900);
362        assert_eq!(backoff_secs(9), 900);
363    }
364
365    #[tokio::test]
366    async fn waits_for_the_backoff_without_pushing() {
367        let store = Arc::new(TaskStore::open_memory().await.unwrap());
368        let fx = fixture();
369        break_remote(&fx.remote);
370        let task_id = pending_task(&store, &fx, 1).await;
371
372        // The first look starts the timer, the second finds it running
373        assert_eq!(
374            retry_pending_push(&store, "", &task_id).await,
375            PushRetry::Wait
376        );
377        assert_eq!(
378            retry_pending_push(&store, "", &task_id).await,
379            PushRetry::Wait
380        );
381        assert_eq!(stored(&store, &task_id).await.push_failures, 1);
382    }
383
384    #[tokio::test]
385    async fn failures_inside_one_outage_do_not_block_and_the_next_push_lands() {
386        let store = Arc::new(TaskStore::open_memory().await.unwrap());
387        let fx = fixture();
388        break_remote(&fx.remote);
389        let task_id = pending_task(&store, &fx, 1).await;
390        let key = retry_key("", &task_id);
391
392        for expected in [2, 3] {
393            store.kv_set(&key, "0").await.unwrap();
394            assert_eq!(
395                retry_pending_push(&store, "", &task_id).await,
396                PushRetry::Failed
397            );
398            let task = stored(&store, &task_id).await;
399            assert_eq!(task.push_failures, expected);
400            assert!(is_pending(&task));
401        }
402
403        fs::remove_file(fx.remote.join("hooks/pre-receive")).unwrap();
404        store.kv_set(&key, "0").await.unwrap();
405        assert_eq!(
406            retry_pending_push(&store, "", &task_id).await,
407            PushRetry::Pushed
408        );
409        let task = stored(&store, &task_id).await;
410        assert_eq!(task.push_failures, 0);
411        assert!(task.last_error.is_empty());
412        assert!(store.kv_get(&key).await.unwrap().is_none());
413        let heads = Command::new("git")
414            .args(["branch", "--list", "feature"])
415            .current_dir(&fx.remote)
416            .output()
417            .unwrap();
418        assert!(String::from_utf8_lossy(&heads.stdout).contains("feature"));
419    }
420
421    #[tokio::test]
422    async fn the_last_allowed_failure_exhausts() {
423        let store = Arc::new(TaskStore::open_memory().await.unwrap());
424        let fx = fixture();
425        break_remote(&fx.remote);
426        let task_id = pending_task(&store, &fx, 3).await;
427        store.kv_set(&retry_key("", &task_id), "0").await.unwrap();
428
429        assert!(matches!(
430            retry_pending_push(&store, "", &task_id).await,
431            PushRetry::Exhausted(_)
432        ));
433    }
434
435    #[tokio::test]
436    async fn a_failure_that_is_not_transient_is_left_alone() {
437        let store = Arc::new(TaskStore::open_memory().await.unwrap());
438        let fx = fixture();
439        let task_id = pending_task(&store, &fx, 1).await;
440        let store_id = store.resolve_task_id("", &task_id).await.unwrap().unwrap();
441        store
442            .set_fields(
443                store_id,
444                &[(
445                    "last_error",
446                    serde_json::json!("push failed: ! [rejected] feature -> feature (fetch first)"),
447                )],
448            )
449            .await
450            .unwrap();
451
452        assert_eq!(
453            retry_pending_push(&store, "", &task_id).await,
454            PushRetry::NotPending
455        );
456    }
457
458    #[tokio::test]
459    async fn is_pending_when_the_task_already_has_a_pr() {
460        let store = Arc::new(TaskStore::open_memory().await.unwrap());
461        let fx = fixture();
462        let task_id = pending_task(&store, &fx, 1).await;
463        set_pr_number(&store, &task_id, 12).await;
464        assert!(is_pending(&stored(&store, &task_id).await));
465    }
466
467    /// A later commit on a task that already has a PR still retries its push (#4051)
468    #[tokio::test]
469    async fn retries_an_unpushed_commit_when_the_task_already_has_a_pr() {
470        let store = Arc::new(TaskStore::open_memory().await.unwrap());
471        let fx = fixture();
472        extra_unpushed_commit(&fx);
473        let task_id = pending_task(&store, &fx, 1).await;
474        set_pr_number(&store, &task_id, 12).await;
475        let key = retry_key("", &task_id);
476
477        assert_eq!(
478            retry_pending_push(&store, "", &task_id).await,
479            PushRetry::Wait
480        );
481        assert!(!remote_log(&fx).contains("more"));
482
483        store.kv_set(&key, "0").await.unwrap();
484        assert_eq!(
485            retry_pending_push(&store, "", &task_id).await,
486            PushRetry::Pushed
487        );
488        let task = stored(&store, &task_id).await;
489        assert_eq!(task.push_failures, 0);
490        assert!(task.last_error.is_empty());
491        assert_eq!(task.pr_number, Some(12));
492        assert!(remote_log(&fx).contains("more"));
493    }
494}