Compare commits

...
13 Commits
Author SHA1 Message Date
dasemu 8c902e85b7 Merge pull request #15 from Dasemu/development
Release: development into main
2026-11-18 03:28:49 +01:00
dasemu 80ff449f74 Merge pull request #14 from Dasemu/fix/ignored-conflicts-real-files
fix(core): only existing files count as ignored conflicts
2026-11-17 17:26:47 +01:00
dasemuandClaude Opus 5.5 7ed5675a00 fix(core): only existing files count as ignored conflicts
A whole ignored directory (e.g. .claude/) made every incoming file under it a
'would overwrite ignored local files' conflict, even when the file did not
exist locally, so such branches never fast-forwarded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:26:20 +01:00
dasemu 933ad65cf0 Merge pull request #13 from Dasemu/fix/fair-dispatch
fix(daemon): dispatch due repos longest-waiting first
2026-11-17 17:04:20 +01:00
dasemuandClaude Opus 5.5 51450ffa5e fix(daemon): dispatch due repos longest-waiting first
With the worker pool, a full pass every fetch_interval_s re-marked every repo
due 'now' and dispatch went by path, so when a cycle took longer than the
interval the repos late in the alphabet never got a pass (52 of 80 on a real
machine). Keep the earlier due time and dispatch by it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:03:51 +01:00
dasemu 380fff5395 Merge pull request #12 from Dasemu/fix/purge-confirm-slow-passes
fix(daemon): keep purge confirmations across slow pass cycles
2026-11-17 16:19:31 +01:00
dasemuandClaude Opus 5.5 d73f0c9463 fix(daemon): keep purge confirmations across slow pass cycles
A gap of more than 20 min between two confirmations reset the wait, but a
cycle over ~80 repos took ~25 min, so no deletion was ever confirmed.
Only a gap over 6 h starts over now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:19:04 +01:00
dasemu 0f83e9d30b Merge pull request #11 from Dasemu/feat/parallel-sync
feat(daemon): run sync passes on a worker pool
2026-11-17 16:03:10 +01:00
dasemuandClaude Opus 5.5 f16438fa02 feat(daemon): run sync passes on a worker pool
The loop thread schedules and sync.workers threads (default 4) run passes,
so a slow or hanging fetch no longer holds up every other repo. A repo never
has two passes at once; passes go only to idle workers, so pause and backoff
behave as before. Visibility and merged-PR caches are shared without holding
locks across forge requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:02:41 +01:00
dasemu 6e5bee1a95 Merge pull request #10 from Dasemu/feat/prune-merged-without-pr
feat(daemon): prune branches merged without a PR, protect long-lived ones
2026-11-17 15:31:19 +01:00
dasemuandClaude Opus 5.5 a1646bccb7 feat(daemon): prune branches merged without a PR, protect long-lived ones
- Prune a worktree whose pushed tip a merge commit brought into the default
  branch (not on its first-parent history), with no forge needed.
- Never prune or keep from materializing main/master/development/... plus
  sync.prune_protected; this also stops a development->main PR pruning
  development.
- Follow repos transferred or renamed on the forge when listing merged PRs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:29:26 +01:00
dasemu c7899bcdc0 Merge pull request #9 from Dasemu/fix/purge-gitea-ssh-not-found
fix(daemon): recognise Gitea SSH "Cannot find repository" for purge
2026-11-17 15:15:58 +01:00
dasemuandClaude Opus 5.5 2772635ff9 fix(daemon): treat Gitea SSH "Cannot find repository" as a purge hint
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:15:15 +01:00
19 changed files with 770 additions and 183 deletions

No files matched your search

+37
View File
@@ -167,6 +167,23 @@ pub struct Sync {
/// regenerable build output and dependency caches. Any other ignored file keeps it.
#[serde(default = "default_disposable")]
pub prune_disposable: Vec<String>,
/// Extra branches never pruned, on top of the built-in long-lived ones
/// (`prune::default_protected`) and the default branch. See [`Sync::protected_branches`].
#[serde(default)]
pub prune_protected: Vec<String>,
/// How many repos the daemon syncs at the same time (1 to 32). A repo never has two
/// passes at once.
#[serde(default = "default_workers")]
pub workers: usize,
}
impl Sync {
/// Branches never pruned: the built-in long-lived ones plus `prune_protected`.
pub fn protected_branches(&self) -> Vec<String> {
let mut all = crate::prune::default_protected();
all.extend(self.prune_protected.iter().cloned());
all
}
}
impl Default for Sync {
@@ -180,6 +197,8 @@ impl Default for Sync {
purged_dir: default_purged_dir(),
prune_merged: true,
prune_disposable: default_disposable(),
prune_protected: Vec::new(),
workers: default_workers(),
}
}
}
@@ -193,6 +212,9 @@ pub struct ConfigRepo {
fn yes() -> bool {
true
}
fn default_workers() -> usize {
4
}
fn default_debounce() -> u64 {
2000
}
@@ -333,6 +355,12 @@ impl Config {
));
}
}
if !(1..=32).contains(&self.sync.workers) {
return bad(format!(
"sync.workers = {} must be between 1 and 32",
self.sync.workers
));
}
if let Some(d) = self
.sync
.prune_disposable
@@ -457,10 +485,19 @@ name = "grove-config"
let c = Config::parse(base).unwrap();
assert!(c.sync.prune_merged);
assert!(c.sync.prune_disposable.iter().any(|d| d == "target"));
assert!(
c.sync
.protected_branches()
.iter()
.any(|b| b == "development")
);
let own = format!("{base}[sync]\nprune_merged=false\nprune_disposable=[\"out\"]\n");
let c = Config::parse(&own).unwrap();
assert!(!c.sync.prune_merged);
assert_eq!(c.sync.prune_disposable, vec!["out".to_string()]);
let t = format!("{base}[sync]\nprune_protected=[\"release\"]\n");
let p = Config::parse(&t).unwrap().sync.protected_branches();
assert!(p.iter().any(|b| b == "release") && p.iter().any(|b| b == "main"));
for bad in ["\"\"", "\"a/b\"", "\"..\""] {
let t = format!("{base}[sync]\nprune_disposable=[{bad}]\n");
assert!(Config::parse(&t).is_err(), "{bad}");
+104 -26
View File
@@ -1,11 +1,18 @@
//! Removing worktrees whose work was merged through a pull request on the forge.
//! Removing worktrees whose work is already merged.
//!
//! The forge (not git ancestry) says what was merged: squash and rebase merges leave no
//! ancestry, and a branch freshly created from the default branch is an ancestor of it too.
//! A worktree is removed only when its branch is the head of a merged pull request, its tip is
//! that head (or an ancestor of it), and it holds no local work: no uncommitted or untracked
//! files, no ignored files other than regenerable ones (`sync.prune_disposable`), no git
//! operation in progress. The tip is kept under a backup ref before anything is removed.
//! A branch counts as merged when either
//! - it is the head of a pull request merged on the forge and its tip is that head (or an
//! ancestor of it): squash and rebase merges leave no ancestry, so the forge has to say so; or
//! - it was merged without a pull request: its tip was pushed (`<remote>/<branch>` points at it),
//! is a strict ancestor of `<remote>/<default>` and is not on its first-parent history (a
//! merge commit brought it in). A branch created from the default branch with no commits of
//! its own is on that history, so it never counts; neither does a fast-forward merge.
//!
//! Branches named in `sync.prune_protected` (long-lived ones such as `development`) and the
//! default branch are never pruned. A worktree is removed only when it holds no local work: no
//! uncommitted or untracked files, no ignored files other than regenerable ones
//! (`sync.prune_disposable`), no git operation in progress. The tip is kept under a backup ref
//! before anything is removed.
use crate::git::{Git, GitError};
use crate::inspect::worktrees;
@@ -27,18 +34,42 @@ pub enum Pruned {
/// Worktree removed and local branch deleted; the tip is kept under `backup_ref`.
Removed {
branch: String,
pr: u64,
/// The merged pull request; `None` when merged into the default branch without one.
pr: Option<u64>,
path: PathBuf,
backup_ref: String,
},
/// Merged, but the worktree holds something that is not on the forge: kept.
Kept {
branch: String,
pr: u64,
pr: Option<u64>,
why: String,
},
}
/// How a pruned branch was merged, for messages ("merged in PR #3").
pub fn merged_how(pr: Option<u64>) -> String {
match pr {
Some(n) => format!("merged in PR #{n}"),
None => "merged into the default branch".into(),
}
}
/// Long-lived branches that are never pruned; `sync.prune_protected` adds to them.
pub fn default_protected() -> Vec<String> {
[
"main",
"master",
"development",
"develop",
"dev",
"staging",
"production",
]
.map(String::from)
.to_vec()
}
/// Backup-ref kind of a pruned branch (`refs/sync-backup/<machine>/<stamp>/merged/<branch>`).
const KIND: &str = "merged";
@@ -94,19 +125,54 @@ fn is_ancestor(g: &Git, a: &str, b: &str) -> bool {
matches!(g.probe(&["merge-base", "--is-ancestor", a, b]), Ok(Some(_)))
}
/// Removes the worktrees of the bare-layout repo at `root` whose branch was merged on the forge
/// (see the module docs). Only worktrees inside `root` are touched, never the one of the
/// default branch (`.bare`'s HEAD).
fn resolve(g: &Git, r: &str) -> Option<String> {
g.probe(&["rev-parse", "-q", "--verify", &format!("{r}^{{commit}}")])
.ok()
.flatten()
}
/// Merged without a pull request: `tip` was pushed as `<remote>/<branch>`, is a strict ancestor
/// of `<remote>/<default>` and is not on its first-parent history (a merge commit brought it).
fn merged_by_ancestry(g: &Git, remote: &str, default: &str, branch: &str, tip: &str) -> bool {
let Some(base) = resolve(g, &format!("refs/remotes/{remote}/{default}")) else {
return false;
};
resolve(g, &format!("refs/remotes/{remote}/{branch}")).as_deref() == Some(tip)
&& base != tip
&& is_ancestor(g, tip, &base)
&& !on_first_parent_chain(g, tip, &base)
}
/// True when `tip` is on the first-parent history of `base`: the default branch passed through
/// it. That is a branch created from the default branch with no commits of its own (or merged
/// by fast-forward, which the PR path still covers), so ancestry says nothing about a merge.
fn on_first_parent_chain(g: &Git, tip: &str, base: &str) -> bool {
// On error, assume it is (never prune on doubt).
g.run(&["rev-list", "--first-parent", base])
.map_or(true, |l| l.lines().any(|c| c == tip))
}
/// What to prune and what to keep.
pub struct Rules<'a> {
/// Remote whose default branch and branches the ancestry rule compares against.
pub remote: &'a str,
/// Heads of pull requests merged on the forge (may be empty: unknown).
pub merged: &'a [MergedHead],
/// Ignored file/directory names that do not count as local work.
pub disposable: &'a [String],
/// Branch names never pruned.
pub protected: &'a [String],
}
/// Removes the worktrees of the bare-layout repo at `root` whose branch is already merged (see
/// the module docs). Only worktrees inside `root` are touched, never the one of the default
/// branch (`.bare`'s HEAD) nor protected branches.
pub fn prune_merged(
root: &Path,
merged: &[MergedHead],
disposable: &[String],
rules: &Rules,
machine: &str,
stamp: &str,
) -> Result<Vec<Pruned>, GitError> {
if merged.is_empty() {
return Ok(vec![]);
}
let bare = root.join(".bare");
let g = Git::new(&bare);
let default = g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?;
@@ -116,27 +182,37 @@ pub fn prune_merged(
let Some(branch) = wt.branch.as_deref() else {
continue;
};
if default.as_deref() == Some(branch) || !wt.path.starts_with(&canonical_root) {
if default.as_deref() == Some(branch)
|| rules.protected.iter().any(|p| p == branch)
|| !wt.path.starts_with(&canonical_root)
{
continue;
}
let Ok(tip) = g.run(&["rev-parse", &format!("refs/heads/{branch}")]) else {
continue;
};
// The newest merged PR of this branch whose head contains the local tip.
let Some(pr) = merged
// The newest merged PR of this branch whose head contains the local tip, else a merge
// without a PR.
let pr = rules
.merged
.iter()
.filter(|m| m.branch == branch)
.find(|m| m.sha == tip || is_ancestor(&g, &tip, &m.sha))
else {
.map(|m| m.number);
if pr.is_none()
&& !default
.as_deref()
.is_some_and(|d| merged_by_ancestry(&g, rules.remote, d, branch, &tip))
{
continue;
};
}
if !wt.path.is_dir() {
continue;
}
if let Some(why) = local_work(&wt.path, disposable)? {
if let Some(why) = local_work(&wt.path, rules.disposable)? {
out.push(Pruned::Kept {
branch: branch.to_string(),
pr: pr.number,
pr,
why,
});
continue;
@@ -148,7 +224,7 @@ pub fn prune_merged(
g.run(&["branch", "-D", branch])?;
out.push(Pruned::Removed {
branch: branch.to_string(),
pr: pr.number,
pr,
path: wt.path.clone(),
backup_ref: bref,
});
@@ -158,11 +234,12 @@ pub fn prune_merged(
/// Branches `materialize` must not bring back: the remote tip is the head of a merged PR, or
/// the tip this machine pruned (its `merged/<branch>` backup ref). New commits pushed to the
/// branch after the merge make it materialize again.
/// branch after the merge make it materialize again. Protected branches are never settled.
pub fn settled_branches(
bare: &Path,
remote: &str,
merged: &[MergedHead],
protected: &[String],
machine: &str,
) -> Result<Vec<String>, GitError> {
let g = Git::new(bare);
@@ -186,6 +263,7 @@ pub fn settled_branches(
.lines()
.filter_map(|l| l.split_once(' '))
.filter_map(|(sha, r)| Some((sha, r.strip_prefix(&prefix)?)))
.filter(|(_, b)| !protected.iter().any(|p| p == b))
.filter(|(sha, b)| {
merged.iter().any(|m| m.branch == *b && m.sha == *sha)
|| pruned.iter().any(|(s, pb)| pb == b && s == sha)
+17
View File
@@ -45,6 +45,7 @@ pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, Gi
"-z",
])?;
let ignored: Vec<&str> = ignored.split('\0').filter(|p| !p.is_empty()).collect();
let top = std::path::PathBuf::from(g.run(&["rev-parse", "--show-toplevel"])?);
Ok(added
.into_iter()
.filter(|a| {
@@ -52,10 +53,26 @@ pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, Gi
.iter()
.any(|i| a == i || (i.ends_with('/') && a.starts_with(i)))
})
// An ignored directory (`.claude/`) only covers the path: there is something to
// overwrite only if the file, or a file where one of its parent directories goes, exists.
.filter(|a| occupied(&top, a))
.map(String::from)
.collect())
}
/// True when writing `rel` under `top` would replace something on disk: the path itself
/// exists, or one of its parents exists as something other than a directory.
fn occupied(top: &Path, rel: &str) -> bool {
let path = top.join(rel);
if path.symlink_metadata().is_ok() {
return true;
}
path.ancestors()
.skip(1)
.take_while(|p| p.starts_with(top) && *p != top)
.any(|p| p.symlink_metadata().is_ok_and(|m| !m.is_dir()))
}
fn current_branch(g: &Git) -> Result<String, GitError> {
g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
.ok_or_else(|| GitError::Other("detached HEAD".into()))
+4 -1
View File
@@ -47,7 +47,10 @@ fn temp_index_path() -> PathBuf {
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
std::env::temp_dir().join(format!("grove-index-{}-{nanos}", std::process::id()))
// A counter too: daemon workers snapshot several repos at once.
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::env::temp_dir().join(format!("grove-index-{}-{nanos}-{n}", std::process::id()))
}
/// Tree of everything in the worktree (tracked changes and untracked files, not ignored ones),
+14 -4
View File
@@ -4,7 +4,7 @@
use crate::git::{Git, GitError};
use crate::inspect::{facts, state, worktrees};
use crate::prune::{MergedHead, Pruned, prune_merged, settled_branches};
use crate::prune::{MergedHead, Pruned, Rules, prune_merged, settled_branches};
use crate::receive::{
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
materialize_except, push_snapshot, receive,
@@ -32,6 +32,10 @@ pub struct Options {
pub merged: Vec<MergedHead>,
/// Names of ignored files/directories that do not count as local work when pruning.
pub disposable: Vec<String>,
/// Prune worktrees of merged branches (bare layout only, see `prune`).
pub prune: bool,
/// Branch names never pruned.
pub protected: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
@@ -82,14 +86,20 @@ pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
}
}
if bare_layout && rep.fetch_error.is_none() && !o.offline {
match prune_merged(path, &o.merged, &o.disposable, &o.machine, &o.stamp) {
if bare_layout && o.prune && rep.fetch_error.is_none() && !o.offline {
let rules = Rules {
remote: &o.remote,
merged: &o.merged,
disposable: &o.disposable,
protected: &o.protected,
};
match prune_merged(path, &rules, &o.machine, &o.stamp) {
Ok(p) => rep.pruned = p,
Err(e) => rep.fetch_error = Some(format!("prune merged: {e}")),
}
}
if bare_layout && o.materialize && rep.fetch_error.is_none() {
let skip = settled_branches(&gitdir, &o.remote, &o.merged, &o.machine);
let skip = settled_branches(&gitdir, &o.remote, &o.merged, &o.protected, &o.machine);
match skip.and_then(|skip| materialize_except(path, &o.remote, &skip)) {
Ok(m) => rep.materialized = m,
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
+78 -4
View File
@@ -2,7 +2,7 @@ mod common;
use common::*;
use grove_core::git::Git;
use grove_core::migrate::migrate;
use grove_core::prune::{MergedHead, Pruned, prune_merged};
use grove_core::prune::{MergedHead, Pruned, Rules, default_protected, prune_merged};
use grove_core::sync::{Options, sync_repo};
use std::fs;
use std::path::{Path, PathBuf};
@@ -58,6 +58,8 @@ fn opts(stamp: &str, merged: Vec<MergedHead>) -> Options {
push_snapshots: false,
merged,
disposable: vec!["target".into()],
prune: true,
protected: default_protected(),
}
}
@@ -119,7 +121,7 @@ fn a_squash_merged_worktree_is_removed_and_not_brought_back() {
else {
panic!("{:?}", rep.pruned);
};
assert_eq!((branch.as_str(), *pr), ("feat/x", 7));
assert_eq!((branch.as_str(), *pr), ("feat/x", Some(7)));
assert!(!wt.exists() && !has_branch(&w.root, "feat/x"));
let bare = Git::new(w.root.join(".bare"));
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
@@ -215,10 +217,82 @@ fn an_older_tip_is_pruned_but_the_default_branch_and_outside_worktrees_never_are
head(5, "main", &main_tip),
head(6, "o", &tip_o),
];
let pruned = prune_merged(&w.root, &merged, &[], "me", "t").unwrap();
let rules = Rules {
remote: "origin",
merged: &merged,
disposable: &[],
protected: &[],
};
let pruned = prune_merged(&w.root, &rules, "me", "t").unwrap();
assert!(
matches!(pruned.as_slice(), [Pruned::Removed { branch, pr: 4, .. }] if branch == "f"),
matches!(pruned.as_slice(), [Pruned::Removed { branch, pr: Some(4), .. }] if branch == "f"),
"{pruned:?}"
);
assert!(w.root.join("main").exists() && ext.exists());
}
#[test]
fn a_branch_merged_without_a_pr_is_removed_but_protected_and_fresh_ones_are_not() {
let w = world();
let tip = push_branch(&w, "feat/ff");
push_branch(&w, "development");
push_branch(&w, "wip");
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
// A branch at the default branch's tip has nothing of its own yet.
w.dev.run(&["push", "-q", "origin", "main:fresh"]).unwrap();
// Merged into main without a pull request (no forge answer at all), with `development`
// (long-lived, protected); `wip` is not merged.
for b in ["feat/ff", "development"] {
w.dev
.run(&["merge", "-q", "--no-ff", "-m", "m", b])
.unwrap();
}
w.dev.run(&["push", "-q", "origin", "main"]).unwrap();
w.dev.run(&["push", "-q", "origin", "main:fresh2"]).unwrap();
let rep = sync_repo(&w.root, &opts("s2", vec![])).unwrap();
assert!(rep.fetch_error.is_none(), "{:?}", rep.fetch_error);
let [
Pruned::Removed {
branch,
pr: None,
backup_ref,
..
},
] = rep.pruned.as_slice()
else {
panic!("{:?}", rep.pruned);
};
assert_eq!(branch, "feat/ff");
let bare = Git::new(w.root.join(".bare"));
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
assert!(!w.root.join("feat-ff").exists() && !has_branch(&w.root, "feat/ff"));
for d in ["development", "wip", "fresh2"] {
assert!(w.root.join(d).exists(), "{d}");
}
// `feat/ff` stays on the remote and is not materialized again. `fresh` (materialized in
// s2) has no commits of its own: main's first-parent history passed through its tip, so it
// is not taken for a merge although main moved past it.
let rep = sync_repo(&w.root, &opts("s3", vec![])).unwrap();
assert!(rep.pruned.is_empty(), "{:?}", rep.pruned);
assert!(!w.root.join("feat-ff").exists());
assert!(w.root.join("fresh").exists() && w.root.join("fresh2").exists());
}
#[test]
fn a_protected_branch_is_kept_even_as_the_head_of_a_merged_pr() {
let w = world();
let tip = push_branch(&w, "development");
squash_merge(&w, "development");
// Not materialized yet: a merged PR head must not keep a protected branch away.
let rep = sync_repo(&w.root, &opts("s1", vec![head(9, "development", &tip)])).unwrap();
assert!(
w.root.join("development").exists(),
"{:?}",
rep.materialized
);
let rep = sync_repo(&w.root, &opts("s2", vec![head(9, "development", &tip)])).unwrap();
assert!(rep.pruned.is_empty(), "{:?}", rep.pruned);
assert!(w.root.join("development").exists());
}
+48
View File
@@ -353,6 +353,52 @@ fn fast_forward_declines_instead_of_overwriting_local_ignored_file() {
);
}
#[test]
fn files_new_in_an_ignored_directory_do_not_block_a_fast_forward() {
let w = world();
commit(&w.g1, "tool/settings.json", "{}\n");
w.g1.run(&["push", "-q"]).unwrap();
// The whole directory is ignored and exists locally, but not the incoming file.
fs::write(w.d2.join(".git/info/exclude"), "tool/\n").unwrap();
fs::create_dir_all(w.d2.join("tool/cache")).unwrap();
fs::write(w.d2.join("tool/cache/x"), "local\n").unwrap();
fetch(&w.d2, REMOTE).unwrap();
assert!(
matches!(
receive(&w.d2, "m2", "t").unwrap(),
Received::FastForwarded { .. }
),
"nothing local would be overwritten"
);
assert_eq!(
fs::read_to_string(w.d2.join("tool/settings.json")).unwrap(),
"{}\n"
);
assert_eq!(
fs::read_to_string(w.d2.join("tool/cache/x")).unwrap(),
"local\n"
);
}
#[test]
fn an_existing_file_in_an_ignored_directory_still_blocks_a_fast_forward() {
let w = world();
commit(&w.g1, "tool/settings.json", "theirs\n");
w.g1.run(&["push", "-q"]).unwrap();
fs::write(w.d2.join(".git/info/exclude"), "tool/\n").unwrap();
fs::create_dir_all(w.d2.join("tool")).unwrap();
fs::write(w.d2.join("tool/settings.json"), "mine\n").unwrap();
fetch(&w.d2, REMOTE).unwrap();
assert!(matches!(
receive(&w.d2, "m2", "t").unwrap(),
Received::Declined(_)
));
assert_eq!(
fs::read_to_string(w.d2.join("tool/settings.json")).unwrap(),
"mine\n"
);
}
#[test]
fn snapshot_apply_declines_instead_of_overwriting_local_ignored_file() {
let w = world();
@@ -388,6 +434,8 @@ fn archive_and_receive_in_one_pass_do_not_collide_on_backup_refs() {
push_snapshots: true,
merged: vec![],
disposable: vec![],
prune: false,
protected: vec![],
};
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
commit(&w.g1, "z.txt", "z\n");
+2
View File
@@ -18,6 +18,8 @@ fn opts(machine: &str, stamp: &str) -> Options {
push_snapshots: true,
merged: vec![],
disposable: vec![],
prune: false,
protected: vec![],
}
}
+183 -57
View File
@@ -1,6 +1,7 @@
//! Event loop: file events are debounced per repo, a periodic pass covers fetches and anything
//! the watcher missed, failures back off exponentially. One worker thread runs the sync passes,
//! so passes never overlap.
//! the watcher missed, failures back off exponentially. The loop thread schedules; a pool of
//! `sync.workers` threads runs the passes, several repos at once but never two passes of the
//! same repo.
use crate::activity::{Activity, now_secs};
use crate::discover::{discover, group_of, is_ready, subdirs};
@@ -9,7 +10,7 @@ use crate::merged::{MergedCache, has_candidates};
use crate::purge;
use crate::visibility::{RealForge, Visibility, snapshot_gate};
use grove_core::config::Config;
use grove_core::prune::Pruned;
use grove_core::prune::{Pruned, merged_how};
use grove_core::receive::Received;
use grove_core::sync::{Options, sync_repo};
use notify::{EventKind, RecursiveMode, Watcher};
@@ -99,9 +100,72 @@ pub enum Msg {
Rescan,
/// Sync one repo (or all) as soon as possible.
SyncNow(Option<PathBuf>),
/// A worker finished a pass: consecutive failures (0 = success), and whether it was offline.
Done {
repo: PathBuf,
failures: u32,
offline: bool,
},
Shutdown,
}
/// One pass for a worker to run.
struct Job {
repo: PathBuf,
offline: bool,
}
/// Starts `n` threads that run passes from `jobs` and report each one as [`Msg::Done`].
fn spawn_workers(
n: usize,
jobs: Receiver<Job>,
cfg: &Arc<Config>,
st: &Arc<Settings>,
visibility: &Arc<Visibility>,
forge: &Arc<ForgeMemory>,
ctx: &Ctx,
) -> Vec<JoinHandle<()>> {
let jobs = Arc::new(Mutex::new(jobs));
(0..n)
.map(|_| {
let (jobs, cfg, st, visibility, forge, ctx) = (
jobs.clone(),
cfg.clone(),
st.clone(),
visibility.clone(),
forge.clone(),
ctx.clone(),
);
std::thread::spawn(move || {
loop {
// The lock is held only while waiting for the next job.
let job = jobs.lock().unwrap().recv();
let Ok(Job { repo, offline }) = job else {
break;
};
// A panicking pass must still report back, or its repo is never synced again.
let failures = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
pass(&repo, &cfg, &st, &visibility, offline, &forge, &ctx)
}))
.unwrap_or_else(|_| {
ctx.activity.log(
"error",
Some(&repo.display().to_string()),
"sync pass panicked; retried with backoff",
);
1
});
let _ = ctx.tx.send(Msg::Done {
repo,
failures,
offline,
});
}
})
})
.collect()
}
#[derive(Clone)]
pub struct Ctx {
pub shared: Arc<Mutex<Shared>>,
@@ -337,6 +401,7 @@ fn rescan(
root: &Path,
groups: &[String],
watch: &mut Watch,
running: &HashSet<PathBuf>,
ctx: &Ctx,
) -> (Vec<PathBuf>, Vec<PathBuf>) {
// Shallow watches first, then discover: a `.bare` created in a child between the two steps
@@ -353,8 +418,16 @@ fn rescan(
}
}
watch.sync(&wanted, false, ctx);
let d = discover(root, groups);
let found = d.managed;
let mut d = discover(root, groups);
// A repo whose pass is running may hold `.grove-busy` (purge) for a moment: it is judged
// when the pass reports back, not now.
d.stalled.retain(|r| !running.contains(r));
let mut found = d.managed;
for r in running {
if !found.contains(r) && r.is_dir() {
found.push(r.clone());
}
}
for r in &d.stalled {
if watch.warned_stalled.insert(r.clone()) {
ctx.activity.log(
@@ -409,7 +482,26 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
let root = cfg.root_path();
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect();
let mut visibility = Visibility::load(st.visibility_cache.clone());
let cfg = Arc::new(cfg);
let st = Arc::new(st);
let visibility = Arc::new(Visibility::load(st.visibility_cache.clone()));
// Deletions being confirmed and merged pull requests, per repo.
let forge = Arc::new(ForgeMemory::default());
let (jobs, job_rx) = channel::<Job>();
let workers = spawn_workers(
cfg.sync.workers.max(1),
job_rx,
&cfg,
&st,
&visibility,
&forge,
&ctx,
);
// Repos a worker is running a pass for: never scheduled twice.
let mut running: HashSet<PathBuf> = HashSet::new();
// Repos whose `sync` was requested while their pass ran: that pass's failure sets no backoff.
let mut sync_asked: HashSet<PathBuf> = HashSet::new();
let pool = cfg.sync.workers.max(1);
let mut watch = make_watch(
ctx.tx.clone(),
cfg.sync.ignore_extra.clone(),
@@ -417,7 +509,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
groups.clone(),
&ctx,
);
rescan(&root, &groups, &mut watch, &ctx);
rescan(&root, &groups, &mut watch, &running, &ctx);
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
@@ -429,14 +521,16 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let mut next_full = Instant::now();
// When a debounced rediscovery is due (set by the first event of a burst, never pushed back).
let mut rescan_at: Option<Instant> = None;
// Deletions being confirmed and merged pull requests, per repo.
let mut forge = ForgeMemory::default();
loop {
'main: loop {
let now = Instant::now();
// With every worker busy nothing can start before a `Done` arrives: due repos must not
// shorten the wait (that would spin).
let idle = running.len() < pool;
let wake = due_at
.values()
.copied()
.iter()
.filter(|(r, _)| idle && !running.contains(*r))
.map(|(_, t)| *t)
.chain([next_full])
.chain(rescan_at)
.min()
@@ -467,19 +561,44 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
}
Ok(Msg::SyncNow(Some(r))) => {
backoff_until.remove(&r);
if running.contains(&r) {
sync_asked.insert(r.clone());
}
due_at.insert(r, Instant::now());
}
Ok(Msg::SyncNow(None)) => {
backoff_until.clear();
sync_asked.extend(running.iter().cloned());
next_full = Instant::now();
}
Ok(Msg::Done {
repo,
failures,
offline,
}) => {
running.remove(&repo);
let asked = sync_asked.remove(&repo);
if !is_ready(&repo) {
// It vanished mid-pass (or was purged): whatever the pass reported is moot.
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
} else if !offline {
if failures == 0 || asked {
backoff_until.remove(&repo);
} else {
let wait = Duration::from_secs(5u64.saturating_mul(1 << failures.min(6)))
.min(MAX_BACKOFF);
backoff_until.insert(repo, Instant::now() + wait);
}
}
}
Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
}
// Discovery also runs while paused so the status stays current; only syncing stops.
if rescan_at.is_some_and(|t| t <= Instant::now()) {
rescan_at = None;
let (found, added) = rescan(&root, &groups, &mut watch, &ctx);
let (found, added) = rescan(&root, &groups, &mut watch, &running, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
for r in added {
due_at.insert(r, Instant::now());
@@ -491,20 +610,31 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let now = Instant::now();
if now >= next_full {
// Safety net for events the watcher missed (one `read_dir` per group).
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
// A repo still waiting keeps its earlier due time, so it is not overtaken.
for r in found {
due_at.insert(r, now);
due_at
.entry(r)
.and_modify(|t| *t = (*t).min(now))
.or_insert(now);
}
next_full = now + fetch_every;
}
let mut due: Vec<PathBuf> = due_at
// A repo whose pass is running stays due and is dispatched when that pass is done.
// Longest waiting first: with more due repos than workers, the order decides who waits.
let mut due: Vec<(Instant, PathBuf)> = due_at
.iter()
.filter(|(_, t)| **t <= now)
.map(|(r, _)| r.clone())
.filter(|(r, t)| **t <= now && !running.contains(*r))
.map(|(r, t)| (*t, r.clone()))
.collect();
due.sort();
for r in due {
for (_, r) in due {
// Only as many passes as idle workers: the rest stay due, so pause stops them and
// `offline` is decided when a pass really starts.
if running.len() >= pool {
break;
}
if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
due_at.remove(&r);
continue;
@@ -513,35 +643,24 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
first_at.remove(&r);
if !is_ready(&r) {
// Removed or migrated away since the last discovery: drop it, no error.
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
continue;
}
// While backing off after a failure, still snapshot local work (no network needed);
// the network is retried at the first pass after the backoff expires.
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
let failures = pass(&r, &cfg, &st, &mut visibility, offline, &mut forge, &ctx);
if !is_ready(&r) {
// It vanished mid-pass: whatever the pass reported is moot.
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
continue;
}
if offline {
continue;
}
if failures == 0 {
backoff_until.remove(&r);
} else {
let wait =
Duration::from_secs(5u64.saturating_mul(1 << failures.min(6))).min(MAX_BACKOFF);
backoff_until.insert(r, Instant::now() + wait);
}
if ctx.shared.lock().unwrap().paused {
break;
running.insert(r.clone());
if jobs.send(Job { repo: r, offline }).is_err() {
break 'main;
}
}
}
// Workers finish the pass they are running; nothing is cut short.
drop(jobs);
for w in workers {
let _ = w.join();
}
ctx.activity.log("stop", None, "daemon stopped");
}
@@ -557,11 +676,12 @@ fn forget_removed(
backoff_until.retain(|r, _| found.contains(r));
}
/// What the daemon remembers between passes about each repo's forge (in memory only).
/// What the daemon remembers between passes about each repo's forge (in memory only), shared
/// by the workers.
#[derive(Default)]
struct ForgeMemory {
/// Repos whose forge first confirmed their deletion at this time (see `purge`).
gone_since: HashMap<PathBuf, (u64, u64)>,
gone_since: Mutex<HashMap<PathBuf, (u64, u64)>>,
/// Merged pull requests per repo (see `merged`).
merged: MergedCache,
}
@@ -571,9 +691,9 @@ fn pass(
repo: &Path,
cfg: &Config,
st: &Settings,
visibility: &mut Visibility,
visibility: &Visibility,
offline: bool,
forge: &mut ForgeMemory,
forge: &ForgeMemory,
ctx: &Ctx,
) -> u32 {
let ForgeMemory { gone_since, merged } = forge;
@@ -632,6 +752,8 @@ fn pass(
push_snapshots,
merged: merged_heads,
disposable: cfg.sync.prune_disposable.clone(),
prune: cfg.sync.prune_merged,
protected: cfg.sync.protected_branches(),
};
let result = sync_repo(repo, &opts);
if !offline && purge_if_gone(repo, cfg, st, &result, gone_since, ctx) {
@@ -713,12 +835,13 @@ fn pass(
"pruned_merged",
Some(&name),
format!(
"{branch}: merged in PR #{pr}; removed {} (tip kept in {backup_ref})",
"{branch}: {}; removed {} (tip kept in {backup_ref})",
merged_how(*pr),
path.display()
),
),
Pruned::Kept { branch, pr, why } => {
kept.push(format!("{branch}: merged in PR #{pr} but kept: {why}"))
kept.push(format!("{branch}: {} but kept: {why}", merged_how(*pr)))
}
}
}
@@ -763,7 +886,7 @@ fn purge_if_gone(
cfg: &Config,
st: &Settings,
result: &Result<grove_core::sync::SyncReport, grove_core::git::GitError>,
gone_since: &mut HashMap<PathBuf, (u64, u64)>,
gone_since: &Mutex<HashMap<PathBuf, (u64, u64)>>,
ctx: &Ctx,
) -> bool {
let name = repo.display().to_string();
@@ -773,14 +896,14 @@ fn purge_if_gone(
};
if !hint || cfg.sync.purged_dir.is_empty() {
if matches!(result, Ok(rep) if rep.fetch_error.is_none()) {
gone_since.remove(repo);
gone_since.lock().unwrap().remove(repo);
}
return false;
}
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
Ok(true) => {}
Ok(false) => {
gone_since.remove(repo);
gone_since.lock().unwrap().remove(repo);
return false;
}
// Cannot tell (network, token): keep whatever was confirmed before.
@@ -788,13 +911,16 @@ fn purge_if_gone(
}
let now = now_secs();
let window = purge::CONFIRM_AFTER_SECS;
let entry = gone_since.entry(repo.to_path_buf()).or_insert((now, now));
if now.saturating_sub(entry.1) > 2 * window {
// Stale: start over.
*entry = (now, now);
}
entry.1 = now;
let first = entry.0;
let first = {
let mut map = gone_since.lock().unwrap();
let entry = map.entry(repo.to_path_buf()).or_insert((now, now));
if now.saturating_sub(entry.1) > purge::STALE_AFTER_SECS {
// Stale: start over.
*entry = (now, now);
}
entry.1 = now;
entry.0
};
if first == now {
ctx.activity.log(
"purge_pending",
@@ -813,8 +939,8 @@ fn purge_if_gone(
else {
return false;
};
let gone = |ctx: &Ctx, gone_since: &mut HashMap<PathBuf, (u64, u64)>| {
gone_since.remove(repo);
let gone = |ctx: &Ctx, gone_since: &Mutex<HashMap<PathBuf, (u64, u64)>>| {
gone_since.lock().unwrap().remove(repo);
ctx.shared.lock().unwrap().repos.remove(repo);
};
match purge::move_repo(repo, &dest) {
+29 -18
View File
@@ -12,6 +12,7 @@ use grove_core::inspect::worktrees;
use grove_core::prune::MergedHead;
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// How long a forge answer is reused.
@@ -37,8 +38,8 @@ impl PullSource for RealForge {
name: &str,
) -> Result<Vec<MergedHead>, String> {
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
let pulls = grove_providers::build(pc, token)
.merged_pulls(owner, name)
let forge = grove_providers::build(pc, token);
let pulls = grove_providers::merged_pulls_following_moves(forge.as_ref(), owner, name)
.map_err(|e| e.to_string())?;
Ok(pulls
.into_iter()
@@ -91,10 +92,11 @@ struct Entry {
noted: BTreeSet<String>,
}
/// Per-repo forge answers and notes, held by the daemon loop (in memory only).
/// Per-repo forge answers and notes (in memory only), shared by the daemon's sync workers. The
/// lock is never held across a forge request.
#[derive(Default)]
pub struct MergedCache {
entries: HashMap<PathBuf, Entry>,
entries: Mutex<HashMap<PathBuf, Entry>>,
}
/// Result of [`MergedCache::heads`].
@@ -107,25 +109,31 @@ pub struct Heads {
impl MergedCache {
/// The merged heads of `repo`, asking `src` when the cached answer is older than [`TTL`].
pub fn heads(
&mut self,
&self,
cfg: &Config,
repo: &Path,
remote: &str,
src: &dyn PullSource,
now: Instant,
) -> Heads {
let e = self.entries.entry(repo.to_path_buf()).or_default();
if e.checked
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
{
return Heads {
heads: e.heads.clone(),
new_error: None,
};
let mut entries = self.entries.lock().unwrap();
let e = entries.entry(repo.to_path_buf()).or_default();
if e.checked
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
{
return Heads {
heads: e.heads.clone(),
new_error: None,
};
}
e.checked = Some(now);
}
e.checked = Some(now);
let answer = lookup(cfg, repo, remote, src);
let mut entries = self.entries.lock().unwrap();
let e = entries.entry(repo.to_path_buf()).or_default();
let mut new_error = None;
match lookup(cfg, repo, remote, src) {
match answer {
Ok(h) => {
e.heads = h;
e.error = None;
@@ -145,8 +153,9 @@ impl MergedCache {
/// Of the "kept" notes of this pass, those not logged yet for `repo`. Notes that no longer
/// apply are forgotten, so they are logged again if they come back.
pub fn new_notes(&mut self, repo: &Path, notes: Vec<String>) -> Vec<String> {
let e = self.entries.entry(repo.to_path_buf()).or_default();
pub fn new_notes(&self, repo: &Path, notes: Vec<String>) -> Vec<String> {
let mut entries = self.entries.lock().unwrap();
let e = entries.entry(repo.to_path_buf()).or_default();
let now: BTreeSet<String> = notes.into_iter().collect();
let fresh = now.difference(&e.noted).cloned().collect();
e.noted = now;
@@ -156,6 +165,8 @@ impl MergedCache {
/// The last answer for `repo`, without asking the forge (offline passes).
pub fn cached(&self, repo: &Path) -> Vec<MergedHead> {
self.entries
.lock()
.unwrap()
.get(repo)
.map(|e| e.heads.clone())
.unwrap_or_default()
@@ -217,7 +228,7 @@ mod tests {
asked: RefCell::new(vec![]),
answer: RefCell::new(Ok(vec![head(1)])),
};
let mut c = MergedCache::default();
let c = MergedCache::default();
let t0 = Instant::now();
assert_eq!(c.heads(&cfg, &repo, "origin", &f, t0).heads, vec![head(1)]);
assert_eq!(f.asked.borrow().as_slice(), ["gitea:Org/r"]);
@@ -235,7 +246,7 @@ mod tests {
#[test]
fn notes_are_reported_once_while_they_hold() {
let mut c = MergedCache::default();
let c = MergedCache::default();
let r = Path::new("/r");
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
assert!(c.new_notes(r, vec!["a".into()]).is_empty());
+9
View File
@@ -14,6 +14,10 @@ use std::path::{Path, PathBuf};
/// How long a remote deletion must keep being confirmed before the repo is moved.
pub const CONFIRM_AFTER_SECS: u64 = 600;
/// A confirmation older than this (no check in between, e.g. the forge was unreachable) no
/// longer counts and the wait starts over. Much longer than the time between two passes of
/// one repo, which can exceed 20 minutes with many repos.
pub const STALE_AFTER_SECS: u64 = 6 * 3600;
/// Fetch failures that may mean the remote repo is gone (only a hint; see [`confirmed_gone`]).
pub fn looks_gone(fetch_error: &str) -> bool {
@@ -22,6 +26,7 @@ pub fn looks_gone(fetch_error: &str) -> bool {
"not found",
"does not appear to be a git repository",
"does not exist",
"cannot find repository", // Gitea/Forgejo over SSH
"error: 404",
]
.iter()
@@ -183,6 +188,10 @@ mod tests {
assert!(looks_gone(
"fatal: 'x.git' does not appear to be a git repository"
));
assert!(looks_gone(
"git fetch -q --prune origin failed (Some(128)): error:\nerror: Cannot find \
repository: dasemu/x\nerror:\nfatal: Could not read from remote repository."
));
assert!(!looks_gone(
"ssh: connect to host h port 22: Connection timed out"
));
+70 -58
View File
@@ -15,6 +15,7 @@ use grove_core::sync::git_dir_for;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
/// How long a "private" answer is trusted (a repo can be made public at any time).
pub const PRIVATE_TTL: u64 = 3600;
@@ -223,10 +224,16 @@ impl Entry {
}
}
/// Visibility cache. Owned by the daemon's single worker thread.
/// Visibility cache, shared by the daemon's sync workers. The lock is never held across a
/// forge request, so lookups for different repos run in parallel.
#[derive(Debug, Default)]
pub struct Visibility {
path: Option<PathBuf>,
state: Mutex<Cache>,
}
#[derive(Debug, Default)]
struct Cache {
entries: BTreeMap<String, Entry>,
failed: HashMap<String, (u64, String)>,
logins: HashMap<String, String>,
@@ -242,12 +249,14 @@ impl Visibility {
.unwrap_or_default();
Visibility {
path,
entries,
..Visibility::default()
state: Mutex::new(Cache {
entries,
..Cache::default()
}),
}
}
fn save(&self) {
fn save(&self, entries: &BTreeMap<String, Entry>) {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let Some(path) = &self.path else { return };
@@ -256,7 +265,7 @@ impl Visibility {
}
let tmp = path.with_extension("json.tmp");
let _ = std::fs::remove_file(&tmp);
let Ok(text) = serde_json::to_string_pretty(&self.entries) else {
let Ok(text) = serde_json::to_string_pretty(entries) else {
return;
};
let written = std::fs::OpenOptions::new()
@@ -272,7 +281,7 @@ impl Visibility {
/// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
fn seen(
&mut self,
&self,
pid: &str,
pc: &ProviderCfg,
owner: &str,
@@ -282,34 +291,39 @@ impl Visibility {
) -> Result<Seen, String> {
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase();
if let Some(e) = self.entries.get(&key)
&& e.fresh(now)
{
return Ok(e.seen);
let c = self.state.lock().unwrap();
if let Some(e) = c.entries.get(&key)
&& e.fresh(now)
{
return Ok(e.seen);
}
if let Some((at, why)) = c.failed.get(&key)
&& at.saturating_sub(0) <= now
&& now - at < RETRY
{
return Err(why.clone());
}
}
if let Some((at, why)) = self.failed.get(&key)
&& at.saturating_sub(0) <= now
&& now - at < RETRY
{
return Err(why.clone());
}
match forge.seen(pid, pc, owner, name) {
let answer = forge.seen(pid, pc, owner, name);
let mut c = self.state.lock().unwrap();
match answer {
Ok(seen) => {
self.failed.remove(&key);
self.entries.insert(key, Entry { seen, checked: now });
self.save();
c.failed.remove(&key);
c.entries.insert(key, Entry { seen, checked: now });
self.save(&c.entries);
Ok(seen)
}
Err(why) => {
let why = format!("lookup on {pid:?} failed: {why}");
self.failed.insert(key, (now, why.clone()));
c.failed.insert(key, (now, why.clone()));
Err(why)
}
}
}
/// Visibility of the repo behind one push URL.
pub fn check_url(&mut self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
pub fn check_url(&self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
let Some(id) = parse_remote(url) else {
return Verdict::Unknown("push URL not understood".into());
};
@@ -327,7 +341,7 @@ impl Visibility {
/// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
fn check_mirror(
&mut self,
&self,
cfg: &Config,
group: &str,
pid: &str,
@@ -346,16 +360,20 @@ impl Visibility {
.and_then(|g| g.owner(pid))
{
Some(o) => o.to_string(),
None => match self.logins.get(pid) {
Some(l) => l.clone(),
None => {
let l = forge
.login(pid, pc)
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
self.logins.insert(pid.to_string(), l.clone());
l
None => {
let known = self.state.lock().unwrap().logins.get(pid).cloned();
match known {
Some(l) => l,
None => {
let l = forge
.login(pid, pc)
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
let mut c = self.state.lock().unwrap();
c.logins.insert(pid.to_string(), l.clone());
l
}
}
},
}
};
match self.seen(pid, pc, &owner, name, now, forge) {
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
@@ -395,7 +413,7 @@ pub fn snapshot_gate(
cfg: &Config,
repo: &Path,
remote: &str,
vis: &mut Visibility,
vis: &Visibility,
now: u64,
forge: &dyn Forge,
) -> Result<(), String> {
@@ -559,7 +577,7 @@ owners = { github = "gh-org" }
.unwrap();
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
assert!(e.contains("several"));
let mut v = Visibility::default();
let v = Visibility::default();
let fake = Fake::default().with("o/r", Ok(Seen::Private));
assert!(matches!(
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
@@ -571,7 +589,7 @@ owners = { github = "gh-org" }
#[test]
fn unknown_visibility_is_public_and_withholds_snapshots() {
let c = cfg();
let mut v = Visibility::default();
let v = Visibility::default();
let boom = Fake::default();
for url in [
"https://gitlab.com/o/r.git",
@@ -608,7 +626,7 @@ owners = { github = "gh-org" }
#[test]
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
let c = cfg();
let mut v = Visibility::default();
let v = Visibility::default();
let f = Fake::default().with("o/r", Ok(Seen::Private));
let url = "https://github.com/o/r";
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
@@ -654,7 +672,7 @@ owners = { github = "gh-org" }
#[test]
fn cache_keys_include_provider_and_are_case_normalised() {
let c = cfg();
let mut v = Visibility::default();
let v = Visibility::default();
let f = Fake::default().with("o/r", Ok(Seen::Private));
v.check_url(&c, "https://github.com/O/R.git", 0, &f);
v.check_url(&c, "git@github.com:o/r", 0, &f);
@@ -676,7 +694,7 @@ owners = { github = "gh-org" }
let file = dir.join("visibility.json");
let c = cfg();
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate));
let mut v = Visibility::load(Some(file.clone()));
let v = Visibility::load(Some(file.clone()));
assert_eq!(
v.check_url(&c, "https://github.com/o/r", 50, &f),
Verdict::Public
@@ -684,7 +702,7 @@ owners = { github = "gh-org" }
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let never = Fake::default();
let mut again = Visibility::load(Some(file));
let again = Visibility::load(Some(file));
assert_eq!(
again.check_url(&c, "https://github.com/o/r", 60, &never),
Verdict::Public
@@ -721,22 +739,16 @@ owners = { github = "gh-org" }
let f = Fake::default()
.with("o/r", Ok(Seen::Private))
.with("o/open", Ok(Seen::NotPrivate));
let mut v = Visibility::default();
let gate = |repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
let v = Visibility::default();
let gate = |repo: &Path, v: &Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
let ok = "https://git.example.com:3000/o/r.git";
assert!(gate(&mk(&base, "priv", &[ok], &[]), &mut v).is_ok());
assert!(gate(&mk(&base, "off", &[ok], &[]), &mut v).is_err());
assert!(
gate(
&mk(&base, "all", &["https://unknown.example/o/r"], &[]),
&mut v
)
.is_ok()
);
assert!(gate(&mk(&base, "priv", &[ok], &[]), &v).is_ok());
assert!(gate(&mk(&base, "off", &[ok], &[]), &v).is_err());
assert!(gate(&mk(&base, "all", &["https://unknown.example/o/r"], &[]), &v).is_ok());
// Fetch URL private, but the push goes to a public repo (pushurl).
let e = gate(
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
&mut v,
&v,
);
assert!(e.is_err());
// Private-only without any remote: unknown, withheld.
@@ -744,7 +756,7 @@ owners = { github = "gh-org" }
std::fs::create_dir_all(&bare).unwrap();
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
assert!(
gate(&base.join("priv/none"), &mut v)
gate(&base.join("priv/none"), &v)
.unwrap_err()
.contains("unknown")
);
@@ -760,24 +772,24 @@ owners = { github = "gh-org" }
let f = Fake::default()
.with("o/r", Ok(Seen::Private))
.with("o/open", Ok(Seen::NotPrivate));
let mut v = Visibility::default();
let v = Visibility::default();
let ok = "https://git.example.com:3000/o/r.git";
let open = "https://github.com/o/open";
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]);
assert!(snapshot_gate(&c, &both, "origin", &mut v, 0, &f).is_ok());
assert!(snapshot_gate(&c, &both, "origin", &v, 0, &f).is_ok());
std::fs::remove_dir_all(base.join("priv")).unwrap();
let leaky = mk(&base, "priv", &[ok, open], &[]);
let e = snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).unwrap_err();
let e = snapshot_gate(&c, &leaky, "origin", &v, 0, &f).unwrap_err();
assert!(e.contains("public"), "{e}");
// pushInsteadOf rewrites the push URL to a public repo.
let g = Git::new(leaky.join(".bare"));
g.run(&["remote", "set-url", "--delete", "origin", open])
.unwrap();
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_ok());
assert!(snapshot_gate(&c, &leaky, "origin", &v, 0, &f).is_ok());
g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
.unwrap();
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_err());
assert!(snapshot_gate(&c, &leaky, "origin", &v, 0, &f).is_err());
std::fs::remove_dir_all(&base).unwrap();
}
@@ -789,8 +801,8 @@ owners = { github = "gh-org" }
let _ = std::fs::remove_dir_all(&base);
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
let gate = |f: &Fake| {
let mut v = Visibility::default();
snapshot_gate(&c, &repo, "origin", &mut v, 0, f)
let v = Visibility::default();
snapshot_gate(&c, &repo, "origin", &v, 0, f)
};
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
// No mirror (404): fine. Mirror owner comes from `owners`.
+66
View File
@@ -768,3 +768,69 @@ fn clone_appears_only_when_complete() {
assert!(seen, "cloned repo never managed");
d.shutdown();
}
#[test]
fn a_hanging_fetch_does_not_hold_up_other_repos() {
let w = world("workers", &["pca"]);
// `a-slow` sorts first, so its pass is dispatched first; its fetch hangs for 15 s.
let slow = w.base.join("pca/g/a-slow");
bare_layout(&slow, &w.remote);
let bare = slow.join(".bare");
git(
&bare,
&["remote", "set-url", "origin", "ssh://hang.invalid/x.git"],
);
git(&bare, &["config", "core.sshCommand", "sleep 15; false"]);
let mut cfg = config(&w, "pca", 200, 60);
cfg.sync.workers = 2;
let started = Instant::now();
let d = Daemon::start(cfg, settings(&w, "pca")).unwrap();
fs::write(w.base.join("pca/g/repo/main/new.txt"), "x\n").unwrap();
wait_until("snapshot of the other repo pushed", 10, || {
!git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).is_empty()
});
assert!(started.elapsed() < Duration::from_secs(12));
d.shutdown();
}
#[test]
fn every_repo_gets_a_pass_when_a_cycle_takes_longer_than_the_interval() {
let w = world("fair", &["pca"]);
// Four repos sorting before `g/repo` whose fetch takes 1.5 s each: with one worker a cycle
// takes ~6 s against a 1 s interval.
for n in ["a", "b", "c", "d"] {
let r = w.base.join(format!("pca/g/{n}"));
bare_layout(&r, &w.remote);
git(
&r.join(".bare"),
&[
"config",
"remote.origin.uploadpack",
"sleep 1.5; git-upload-pack",
],
);
}
let mut cfg = config(&w, "pca", 200, 1);
cfg.sync.workers = 1;
let d = Daemon::start(cfg, settings(&w, "pca")).unwrap();
let sock = w.base.join("pca.sock");
let last = |s: &serde_json::Value, name: &str| {
s["repos"]
.as_array()
.unwrap()
.iter()
.find(|r| r["path"].as_str().unwrap().ends_with(&format!("/g/{name}")))
.and_then(|r| r["last_sync"].as_u64())
};
// `repo` keeps getting passes: it is not starved by the slow ones (before, sorted dispatch
// gave every new cycle to `a`..`d` again and `repo` never ran).
let mut seen = Vec::new();
wait_until("two passes of the last repo", 45, || {
let t = last(&status(&sock), "repo");
if t.is_some() && seen.last() != Some(&t) {
seen.push(t);
}
seen.len() >= 2
});
d.shutdown();
}
+24
View File
@@ -158,6 +158,30 @@ pub trait Provider: Send + Sync {
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>>;
}
/// [`Provider::merged_pulls`] that also finds a repo transferred or renamed on the forge: `origin`
/// may still name the old place, which git and the repo endpoint follow by redirect but the
/// pulls endpoint does not. On failure the repo is looked up and, if its current owner/name
/// differ, its pulls are listed under those.
pub fn merged_pulls_following_moves(
p: &dyn Provider,
owner: &str,
name: &str,
) -> Result<Vec<MergedPull>> {
let err = match p.merged_pulls(owner, name) {
Ok(pulls) => return Ok(pulls),
Err(e) => e,
};
match p.get_repo(owner, name) {
Ok(r)
if !r.owner.is_empty()
&& !(r.owner.eq_ignore_ascii_case(owner) && r.name.eq_ignore_ascii_case(name)) =>
{
p.merged_pulls(&r.owner, &r.name)
}
_ => Err(err),
}
}
/// Builds the provider described by `cfg`, using `token`.
pub fn build(cfg: &ProviderCfg, token: String) -> Box<dyn Provider> {
match cfg.kind {
+36
View File
@@ -526,3 +526,39 @@ fn merged_pulls_keep_only_merged_same_repo_heads() {
Error::Api { status: 404, .. }
));
}
#[test]
fn merged_pulls_follow_a_transferred_repo() {
let pulls = r#"[{"number":4,"merged":true,"head":{"ref":"f","sha":"fff","repo":{"full_name":"Org/r"}},"base":{"repo":{"full_name":"Org/r"}}}]"#;
let (url, rx) = mock(vec![
(404, r#"{"message":"not found"}"#),
(
200,
r#"{"name":"r","owner":{"login":"Org"},"private":true}"#,
),
(200, pulls),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
let got = grove_providers::merged_pulls_following_moves(&g, "me", "r").unwrap();
assert_eq!(got.iter().map(|p| p.number).collect::<Vec<_>>(), vec![4]);
let asked: Vec<String> = rx
.try_iter()
.map(|l| l.lines().next().unwrap().to_string())
.collect();
assert!(asked[1].starts_with("GET /api/v1/repos/me/r "), "{asked:?}");
assert!(
asked[2].starts_with("GET /api/v1/repos/Org/r/pulls?"),
"{asked:?}"
);
// Not moved: the original error stands.
let (url, _rx) = mock(vec![
(404, r#"{"message":"not found"}"#),
(404, r#"{"message":"not found"}"#),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
assert!(matches!(
grove_providers::merged_pulls_following_moves(&g, "me", "gone").unwrap_err(),
Error::Api { status: 404, .. }
));
}
+6 -3
View File
@@ -4,7 +4,7 @@ use grove_core::config::{Config, ProviderKind};
use grove_core::git::Git;
use grove_core::inspect::{state, worktrees};
use grove_core::migrate::migrate;
use grove_core::prune::Pruned;
use grove_core::prune::{Pruned, merged_how};
use grove_core::receive::{Applied, Archived, Received};
use grove_core::resolve::{Choice, resolve};
use grove_core::snapshot::{Outcome, take};
@@ -377,6 +377,8 @@ fn main() -> Result<()> {
push_snapshots: true,
merged,
disposable: cfg.sync.prune_disposable.clone(),
prune: cfg.sync.prune_merged,
protected: cfg.sync.protected_branches(),
},
)?;
print_report(&rep)
@@ -531,11 +533,12 @@ fn print_report(rep: &SyncReport) -> Result<()> {
path,
backup_ref,
} => println!(
"pruned {branch}: merged in PR #{pr}, removed {} (backup {backup_ref})",
"pruned {branch}: {}, removed {} (backup {backup_ref})",
merged_how(*pr),
path.display()
),
Pruned::Kept { branch, pr, why } => {
println!("kept {branch}: merged in PR #{pr} but {why}")
println!("kept {branch}: {} but {why}", merged_how(*pr))
}
}
}
+13 -2
View File
@@ -17,8 +17,19 @@ is `grove_core::sync::sync_repo`, the same code the CLI runs. The daemon only de
cannot starve snapshots.
- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply
snapshots, materialize/archive). Also what catches missed events.
- **One worker thread**: passes never overlap. Events that arrive during a pass queue another pass;
it finds nothing to do and ends the chain.
- **Worker pool**: the loop thread only schedules; `sync.workers` threads (default 4, 1 to 32) run
the passes, so a slow or hanging fetch of one repo no longer holds up the others. A repo never
has two passes at once: one that becomes due while its pass runs is dispatched when it ends.
Events that arrive during a pass queue another pass; it finds nothing to do and ends the chain.
Due repos are dispatched longest-waiting first, and a full pass never moves an earlier due
time later, so when a cycle takes longer than `fetch_interval_s` every repo still gets its
turn (dispatching by path starved the repos late in the alphabet).
Passes are handed out only to idle workers, so the rest stay due: pause stops them, and whether
a pass runs offline (backoff) is decided when it starts. A `sync` request for a repo whose pass
is running is not undone by that pass failing. A panicking pass is logged and counts as a
failure. Rediscovery does not drop or flag (stalled) a repo while its pass runs.
The visibility and merged-PR caches are shared and never locked across a forge request.
Shutdown and pause let running passes finish. `workers = 1` is the old sequential behaviour.
- **Failures** (network, auth, git errors) back off exponentially per repo: 10 s, 20 s, ... capped at
5 min, and are logged as `error`. `sync` over IPC clears the backoff. While backing off, changes
are still snapshotted locally (an offline pass); only the network is retried after the backoff.
+4 -3
View File
@@ -127,10 +127,11 @@ A managed repo whose remote was deleted is moved out of the synced tree, never d
purged_dir = "Purged" # default; "" disables the move
```
- Trigger: a fetch fails with a "not found"-style error. That is only a hint: the forge serving
- Trigger: a fetch fails with a "not found"-style error (also Gitea's SSH "Cannot find repository"). That is only a hint: the forge serving
`origin` must then answer 404 while the same token works (`test_connection`), and still do so
`purge::CONFIRM_AFTER_SECS` (10 min) after the first confirmation (a gap of more than twice
that starts over). A working fetch, or the forge seeing the repo again, clears it. Network or
`purge::CONFIRM_AFTER_SECS` (10 min) after the first confirmation (a gap of more than
`STALE_AFTER_SECS`, 6 h, between two confirmations starts over: a pass over many repos can take
longer than 20 min, so a shorter gap never let a deletion be confirmed). A working fetch, or the forge seeing the repo again, clears it. Network or
token errors change nothing.
- Only repos owned by the token's account, or by an organisation named in some group's `owners`
for that provider, are ever moved: someone else's repo turning private or revoking access looks
+26 -7
View File
@@ -1,10 +1,11 @@
# Pruning worktrees merged through a pull request
# Pruning merged worktrees
Worktrees of branches that were pushed, reviewed in a pull request and merged used to stay
forever: `archive_gone` only removes a worktree when its remote branch is deleted, the forge
often keeps the head branch, squash and rebase merges leave no ancestry for git to see, and a
Rust/Node worktree always holds ignored build output that kept it "dirty". The daemon now asks
the forge which pull requests were merged and removes those worktrees itself.
the forge which pull requests were merged and removes those worktrees itself. Branches merged
into the default branch without a pull request (merged locally and pushed) are removed too.
## Config
@@ -14,9 +15,15 @@ prune_merged = true # default
prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".pytest_cache",
".mypy_cache", ".ruff_cache", ".tox", ".gradle", ".next", ".nuxt", ".svelte-kit", ".turbo",
".parcel-cache", "dist", "build", "out", "coverage", ".cache"] # default
prune_protected = [] # default; extra branch names never pruned
```
- `prune_merged = false` turns the feature off.
- `prune_protected`: extra branch names (exact, no globs) never pruned nor kept from being
materialized, added to the built-in `main`, `master`, `development`, `develop`, `dev`,
`staging`, `production` (a `development` -> `main` PR has `development` as its head). The
default branch (`.bare`'s HEAD) never is either. Other long-lived branches (`release/1.2`,
`hotfix/x`) merged back with no new commits are pruned like any other: list them here.
- `prune_disposable`: names (not paths, not globs) of ignored files/directories that are
regenerable and may go with a pruned worktree. Entries must be plain names.
@@ -26,19 +33,29 @@ prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".
requests (GitHub: 100, `merged_at` set; Gitea/Forgejo: 50, `merged: true`), keeping only those
whose head repo is the base repo: fork PRs reuse branch names freely. The repo is found from
`origin`'s fetch URL, matched to a configured provider like the visibility check (`phase6.md`),
with the token from `token::resolve`.
with the token from `token::resolve`. When that fails, the repo is looked up and, if the forge
reports another owner/name (transferred or renamed: git and the repo endpoint follow the old
`origin` by redirect, the pulls endpoint does not), its pulls are listed under the current one.
Without a pull request, a branch counts as merged when its tip was pushed
(`origin/<branch>` points at it), is a strict ancestor of `origin/<default>` and is not on its
first-parent history, i.e. a merge commit brought it in. This needs no forge. A branch created
from the default branch with no commits of its own is on that history and is never pruned this
way; neither is a fast-forward merge (only the PR path catches those).
## When a worktree is removed
All of these must hold (`grove_core::prune::prune_merged`):
1. The repo is bare layout, the fetch of this pass worked, and the pass is not offline.
2. The worktree is on a branch that is not `.bare`'s HEAD (the default branch), and it lives
2. The worktree is on a branch that is not `.bare`'s HEAD (the default branch) nor in
`prune_protected`, and it lives
inside the repo directory (`root/<group>/<repo>/...`, so nested ones such as
`main/.claude/worktrees/x` count). Linked worktrees elsewhere are the user's and are never
touched.
3. A merged PR has that branch as head and its head commit equals the local tip, or contains it
(the PR got more commits from another machine before the merge).
(the PR got more commits from another machine before the merge); or, without a PR, the
ancestry rule above holds.
4. No local work: no staged, modified or untracked file, no git operation in progress
(`index.lock`, rebase, merge, cherry-pick, revert, bisect), and no ignored entry whose name
is not in `prune_disposable` (`.env` keeps it, `target/` does not).
@@ -66,10 +83,12 @@ branch after the merge are new work: the worktree is materialized again.
error changes).
- Offline passes (backoff) prune nothing, but still use the last answer to keep pruned branches
from being materialized.
- Activity log: `pruned_merged` (removed, with the PR, path and backup ref) and `prune_kept`.
- The ancestry rule runs on every online pass, also when the forge lookup fails.
- Activity log: `pruned_merged` (removed, with the PR or "merged into the default branch", path
and backup ref) and `prune_kept`.
`grove sync <path>` does the same in one shot (no cache) and prints `pruned ...` / `kept ...`
lines; a failed lookup is a warning and prunes nothing.
lines; a failed lookup is a warning, and only the ancestry rule applies.
## Validation