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