From 5a490bd822e23f77607f9784acd7aed2d821fbc9 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 10:57:35 +0300 Subject: [PATCH] fix(repo): guard undo, sparse set and sparse disable against untracked files They re-lay tracked files onto disk and silently replaced an untracked or ignored file at the same path, like merge and switch did before #191. They now refuse before any ref, spec or file write. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 4 +- crates/repo/src/oplog.rs | 3 ++ crates/repo/src/replay.rs | 60 ++++++++++++++++++++++++ crates/repo/src/repo.rs | 44 ++++++++++++++++- crates/repo/src/sparse.rs | 20 ++++++-- docs/adr/0049-merge-on-partial-clones.md | 2 +- 6 files changed, 126 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 31044300..b5d7d3e6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -245,9 +245,9 @@ transport-adjacent. The rest, imperatively: sidecars it wrote are listed apart in `.sc/CONFLICT_SIDECARS`; abort, `rebase --continue` and `sc resolve` remove only those, never a `.theirs` file the stop did not write; the completing commit leaves them out of the tree and removes them. -- **A merge, switch, cherry-pick or rebase refuses, before any write, to lay a file or +- **A merge, switch, cherry-pick, rebase, undo or sparse-spec change refuses, before any write, to lay a file or directory onto an untracked or ignored one** (`refuse_untracked_overwrite`); move it - away and retry. Merging into an unborn branch, `undo`, `sparse set` and the conflict stop of a merge into a private branch are not guarded. + away and retry. Merging into an unborn branch and the conflict stop of a merge into a private branch are not guarded. - **Every ref-moving or commit-creating op (including all secret/protect policy ops) is guarded against an in-progress merge/pick/rebase** — finish or abort the in-progress op first. diff --git a/crates/repo/src/oplog.rs b/crates/repo/src/oplog.rs index 79e2bfc7..83dd9209 100644 --- a/crates/repo/src/oplog.rs +++ b/crates/repo/src/oplog.rs @@ -430,6 +430,9 @@ impl Repo { &self.sparse_spec()?, )?; } + // Before any ref moves: the restored tree must not land on a file + // the user owns. + self.refuse_untracked_overwrite("undo", old_root, snap.root)?; Some((snap.root, snap.protection)) } else { None diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index fadfaf71..9a00cdee 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -3433,6 +3433,66 @@ mod tests { remove_root(&root); } + /// `sc undo` re-lays the restored tree; it must not replace an untracked + /// file there. + #[test] + fn undo_refuses_to_overwrite_an_untracked_file() { + let root = tmp_root("guard-undo"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("a.txt"), b"a\n").unwrap(); + std::fs::write(root.join("gone.txt"), b"was tracked\n").unwrap(); + repo.commit("me", "base").unwrap(); + std::fs::remove_file(root.join("gone.txt")).unwrap(); + let tip = repo.commit("me", "deletes gone.txt").unwrap(); + // The user now has their own gone.txt; undoing the commit would bring + // the tracked one back over it. + std::fs::write(root.join("gone.txt"), b"MINE\n").unwrap(); + + let err = repo.undo().unwrap_err(); + assert!( + matches!(&err, Error::InvalidArgument(m) if m.contains("would overwrite")), + "got {err:?}" + ); + assert_eq!(repo.head_tip().unwrap(), Some(tip), "no ref moved"); + assert_eq!(std::fs::read(root.join("gone.txt")).unwrap(), b"MINE\n"); + drop(repo); + remove_root(&root); + } + + /// Widening or disabling a sparse view lays tracked files onto disk: a + /// file the user made at one of those paths must survive, and the spec + /// must stay as it was. + #[test] + fn sparse_set_and_disable_refuse_to_overwrite_an_untracked_file() { + let root = tmp_root("guard-sparse-widen"); + let repo = Repo::init(&root).unwrap(); + std::fs::create_dir_all(root.join("in")).unwrap(); + std::fs::create_dir_all(root.join("out")).unwrap(); + std::fs::write(root.join("in/x.txt"), b"x\n").unwrap(); + std::fs::write(root.join("out/y.txt"), b"tracked y\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.set_sparse(&["in".to_string()], None).unwrap(); + assert!(!root.join("out/y.txt").exists(), "setup: out of view"); + std::fs::create_dir_all(root.join("out")).unwrap(); + std::fs::write(root.join("out/y.txt"), b"MINE\n").unwrap(); + let spec_before = repo.sparse_spec().unwrap(); + + for err in [ + repo.set_sparse(&["in".to_string(), "out".to_string()], None) + .unwrap_err(), + repo.disable_sparse(None).unwrap_err(), + ] { + assert!( + matches!(&err, Error::InvalidArgument(m) if m.contains("would overwrite")), + "got {err:?}" + ); + } + assert_eq!(repo.sparse_spec().unwrap(), spec_before, "spec unchanged"); + assert_eq!(std::fs::read(root.join("out/y.txt")).unwrap(), b"MINE\n"); + drop(repo); + remove_root(&root); + } + #[test] fn rebase_continue_is_not_blocked_by_files_the_stop_wrote() { let root = tmp_root("guard-rebase-continue"); diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index a4a3ed9d..6a732339 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -2015,6 +2015,36 @@ impl Repo { self.refuse_untracked_paths(op, tracked, target.keys()) } + /// Refuse a sparse-spec change (`op`) that would lay a tracked file onto an + /// untracked or ignored one: a path newly in view (`new_view`) that the + /// tree `root` tracks, with something already standing there and the old + /// view (`old_view`) not having laid it out. Same rules as + /// [`Repo::refuse_untracked_overwrite_vs`]. + pub(crate) fn refuse_untracked_for_view_change( + &self, + op: &str, + root: ObjectId, + old_view: &crate::Sparse, + new_view: &crate::Sparse, + ) -> Result<()> { + let partial = self.promisor()?.is_some(); + let (laid_out, target) = { + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + let mut files = |view: &crate::Sparse| -> Result> { + Ok(if partial { + worktree::tree_file_entries_with_perms_sparse_present(&mut store, root, view)? + } else { + worktree::tree_file_entries_with_perms_sparse(&mut store, root, view)? + } + .into_keys() + .collect()) + }; + (files(old_view)?, files(new_view)?) + }; + self.refuse_untracked_paths_in(op, &laid_out, target.iter(), new_view) + } + /// The path-list core of [`Repo::refuse_untracked_overwrite_vs`], for a /// caller that already holds the target's paths (a private branch's /// decrypted tree). @@ -2024,7 +2054,19 @@ impl Repo { tracked: &std::collections::BTreeSet, target: impl Iterator, ) -> Result<()> { - let sparse = self.sparse_spec()?; + self.refuse_untracked_paths_in(op, tracked, target, &self.sparse_spec()?) + } + + /// [`Repo::refuse_untracked_paths`] for the view the write will happen + /// under (`sparse`), which is not the persisted one while a sparse spec is + /// being changed. + pub(crate) fn refuse_untracked_paths_in<'a>( + &self, + op: &str, + tracked: &std::collections::BTreeSet, + target: impl Iterator, + sparse: &crate::Sparse, + ) -> Result<()> { // A path outside the view was never laid out: whatever is on disk // there is the user's, even if the tree tracks it. On a // case-insensitive filesystem a tracked file may answer to another diff --git a/crates/repo/src/sparse.rs b/crates/repo/src/sparse.rs index d5013597..b6b937a6 100644 --- a/crates/repo/src/sparse.rs +++ b/crates/repo/src/sparse.rs @@ -248,9 +248,14 @@ impl Repo { // laid out (ADR-0048). if let Some(snap) = &snap { self.ensure_view(snap.root, &spec)?; - let store_arc = self.vfs().store(); - let mut s = store_arc.lock().unwrap(); - crate::worktree::preflight_view(self.layout(), &mut s, snap.root, &spec)?; + { + let store_arc = self.vfs().store(); + let mut s = store_arc.lock().unwrap(); + crate::worktree::preflight_view(self.layout(), &mut s, snap.root, &spec)?; + } + // Widening lays tracked files onto disk: refuse before anything is + // stored if one would replace a file the user owns. + self.refuse_untracked_for_view_change("sparse set", snap.root, &old_spec, &spec)?; } // Crash safety: record the spec being replaced before the new one is // stored. If the process dies before the re-lay finishes, the marker @@ -338,6 +343,15 @@ impl Repo { .into(), )); } + if let Some(tip) = self.head_tip()? { + let root = self.snapshot(&tip)?.root; + self.refuse_untracked_for_view_change( + "sparse disable", + root, + &self.sparse_spec()?, + &Sparse::default(), + )?; + } clear(self.layout())?; let Some(tip) = self.head_tip()? else { return Ok(Vec::new()); diff --git a/docs/adr/0049-merge-on-partial-clones.md b/docs/adr/0049-merge-on-partial-clones.md index a8fc93a3..8c2ab169 100644 --- a/docs/adr/0049-merge-on-partial-clones.md +++ b/docs/adr/0049-merge-on-partial-clones.md @@ -184,7 +184,7 @@ Replay is a three-way merge with a different base, and `replay_commit` is the on 19. **Completion can drop a newly tracked ignored file.** *Resolved:* completion reads the working tree with the decided root's paths counted as tracked, so an ignore rule cannot hide a file the operation itself added. Test `completing_a_conflicted_pick_keeps_an_added_file_the_parent_ignores`. 20. **A stopped pick or rebase without its decided root.** `PICK_DECIDED_ROOT` and `REBASE_DECIDED_ROOT` are written before the state's in-progress signal, so the state cannot normally be missing. If it is (a lost file, a power loss before the data reached disk), a partial clone's completion refuses, because grafting from the tip would keep the old out-of-view content; `--abort` still works. -21. **A conflict stop overwrites an ignored or untracked file at a plaintext path.** *Resolved for merge, cherry-pick and rebase:* `materialize_conflict_state` refuses, before any write, when a plaintext or sidecar path already exists on disk (as a file or directory, including a leftover sidecar) and the tree the working tree reflects does not track it or the sparse view never materialized it, or when a file stands where a parent directory must be. A lookup that fails counts as untracked. *Also resolved for the clean paths:* `refuse_untracked_overwrite` runs before the first write of a merge (fast-forward, clean and conflict stop), `switch`, cherry-pick and rebase (fast-forward and the fold's final write) and refuses when a file the result adds, or a directory it needs, lands on something the tree the working tree reflects does not track. It reads the working tree only, skips paths outside the sparse view, and leaves a partial-clone gap to `materialize`'s own view check. A symlink at a written path always counts as occupied (a write would follow it out of the tree), and a tracked path outside the sparse view does not excuse a file in the way. Not guarded: merging into an unborn branch (there is no tree to call a file untracked against), `undo` and `sparse set`. The private-branch switch and merge are guarded inside `materialize_private` against the decrypted target paths. Tracking is compared by exact path, plus a case alias of a tracked path that is provably the same file (same device and inode, unix only), so a case-only rename on a case-insensitive filesystem is not refused; a non-unix build still compares exact paths. The private-branch merge stop (`merge_into_private`) writes its files directly and has no such guard. Tests `a_conflict_stop_refuses_to_overwrite_an_untracked_local_copy`, `a_conflict_stop_does_not_treat_an_out_of_view_path_as_materialized`, `a_binary_conflict_stop_refuses_over_an_untracked_sidecar` and `a_conflict_stop_refuses_when_a_file_blocks_a_parent_directory`. +21. **A conflict stop overwrites an ignored or untracked file at a plaintext path.** *Resolved for merge, cherry-pick and rebase:* `materialize_conflict_state` refuses, before any write, when a plaintext or sidecar path already exists on disk (as a file or directory, including a leftover sidecar) and the tree the working tree reflects does not track it or the sparse view never materialized it, or when a file stands where a parent directory must be. A lookup that fails counts as untracked. *Also resolved for the clean paths:* `refuse_untracked_overwrite` runs before the first write of a merge (fast-forward, clean and conflict stop), `switch`, cherry-pick and rebase (fast-forward and the fold's final write) and refuses when a file the result adds, or a directory it needs, lands on something the tree the working tree reflects does not track. It reads the working tree only, skips paths outside the sparse view, and leaves a partial-clone gap to `materialize`'s own view check. A symlink at a written path always counts as occupied (a write would follow it out of the tree), and a tracked path outside the sparse view does not excuse a file in the way. `undo`, `sparse set` and `sparse disable` are guarded the same way (a sparse-spec change against the tree its old view laid out). Not guarded: merging into an unborn branch (there is no tree to call a file untracked against). The private-branch switch and merge are guarded inside `materialize_private` against the decrypted target paths. Tracking is compared by exact path, plus a case alias of a tracked path that is provably the same file (same device and inode, unix only), so a case-only rename on a case-insensitive filesystem is not refused; a non-unix build still compares exact paths. The private-branch merge stop (`merge_into_private`) writes its files directly and has no such guard. Tests `a_conflict_stop_refuses_to_overwrite_an_untracked_local_copy`, `a_conflict_stop_does_not_treat_an_out_of_view_path_as_materialized`, `a_binary_conflict_stop_refuses_over_an_untracked_sidecar` and `a_conflict_stop_refuses_when_a_file_blocks_a_parent_directory`. ## Alternatives considered