Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ unwreck run -- aider
| `unwreck run -- <cmd…>` | Snapshot around any CLI (`--quiet-ms`, default 1500) |
| `unwreck watch` | Same watcher without spawning a child |
| `unwreck snap [-m msg]` | Manual snapshot (always written) |
| `unwreck pin <id>` / `unpin <id>` | Protect / unprotect a snapshot from garbage collection |
| `unwreck pinned` | List protected snapshots |
| `unwreck log [-n 20]` | Timeline, newest last |
| `unwreck diff [N [M]]` | No args: last turn-start vs disk. One id vs disk. Two ids vs each other. `--patch` for unified diffs |
| `unwreck restore <id>` | Make the tree match that snapshot (`--only`, `--force`, `--dry-run`) |
Expand All @@ -88,7 +90,7 @@ keep_turns = 500 # newest N snapshots (default)
keep_days = 30 # also keep anything this new
```

`unwreck gc --keep N` keeps only the newest N for that run. Packs are rewritten only when more than 30% of the file is unreferenced.
`unwreck gc --keep N` keeps only the newest N for that run. Packs are rewritten only when more than 30% of the file is unreferenced. Pinned snapshots are always retained until unpinned.

</details>

Expand Down
72 changes: 71 additions & 1 deletion code/crates/unwreck-store/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ impl Drop for StoreLock {
}

const TIP: &str = "tip.json";
const PINNED: &str = "pinned.json";

/// Compact identity of the latest snapshot, so an unchanged scan can skip reading the
/// full manifest. Missing or corrupt `tip.json` falls back to `latest()`.
Expand Down Expand Up @@ -387,6 +388,43 @@ impl Store {
fs::read(self.root.join(name)).ok()
}

/// Snapshot ids protected from garbage collection.
///
/// A malformed pin list is an error rather than silently risking deletion.
pub fn pinned(&self) -> Result<Vec<u64>> {
let Some(bytes) = self.read_aux(PINNED) else {
return Ok(Vec::new());
};
let mut ids: Vec<u64> = serde_json::from_slice(&bytes)?;
ids.sort_unstable();
ids.dedup();
Ok(ids)
}

/// Pin or unpin a snapshot. Caller must hold `lock()`.
///
/// Returns whether the pin state changed. Pinning requires an existing snapshot.
pub fn set_pinned(&self, id: u64, pinned: bool) -> Result<bool> {
if pinned {
self.read_manifest(id)?;
}
let mut ids = self.pinned()?;
let before = ids.len();
if pinned {
if !ids.contains(&id) {
ids.push(id);
ids.sort_unstable();
}
} else {
ids.retain(|&saved| saved != id);
}
if ids.len() == before {
return Ok(false);
}
self.write_aux(PINNED, &serde_json::to_vec(&ids)?)?;
Ok(true)
}

/// Sorted snapshot ids currently on disk.
pub fn list(&self) -> Result<Vec<u64>> {
let mut ids = Vec::new();
Expand Down Expand Up @@ -501,9 +539,11 @@ impl Store {
pub fn gc(&self, keep: &[u64]) -> Result<GcReport> {
self.commit()?;
let mut rep = GcReport::default();
let mut keep_ids: HashSet<u64> = keep.iter().copied().collect();
keep_ids.extend(self.pinned()?);
let mut live = HashSet::new();
for id in self.list()? {
if keep.contains(&id) {
if keep_ids.contains(&id) {
for e in self.read_manifest(id)?.entries {
if let EntryKind::File { hash, .. } = e.kind {
live.insert(hash);
Expand Down Expand Up @@ -991,6 +1031,36 @@ mod tests {
assert_eq!(s.get(&h).unwrap(), b"old");
}

#[test]
fn pinned_snapshots_survive_gc_until_unpinned() {
let dir = tempfile::tempdir().unwrap();
let s = Store::open(dir.path()).unwrap();
let _l = s.lock().unwrap();
let h = s.put(b"important").unwrap();
let pinned = s
.write_manifest(manual(), vec![file("important.txt", h)], vec![])
.unwrap();
let disposable = s.write_manifest(manual(), vec![], vec![]).unwrap();

assert!(s.set_pinned(pinned.id, true).unwrap());
assert!(!s.set_pinned(pinned.id, true).unwrap());
assert_eq!(s.pinned().unwrap(), vec![pinned.id]);

let report = s.gc(&[disposable.id]).unwrap();
assert_eq!(report.manifests_removed, 0);
assert_eq!(s.read_manifest(pinned.id).unwrap().id, pinned.id);
assert_eq!(s.get(&h).unwrap(), b"important");

assert!(s.set_pinned(pinned.id, false).unwrap());
assert!(!s.set_pinned(pinned.id, false).unwrap());
s.gc(&[disposable.id]).unwrap();
assert!(matches!(
s.read_manifest(pinned.id),
Err(StoreError::NoSnapshot(_))
));
assert!(s.pinned().unwrap().is_empty());
}

#[cfg(unix)]
#[test]
fn store_is_0700_and_files_0600() {
Expand Down
38 changes: 38 additions & 0 deletions code/crates/unwreck/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ enum Cmd {
#[arg(short, long)]
message: Option<String>,
},
/// Protect a snapshot from automatic garbage collection.
Pin { id: u64 },
/// Remove garbage-collection protection from a snapshot.
Unpin { id: u64 },
/// List snapshots protected from garbage collection.
Pinned,
/// List snapshots, newest last.
Log {
#[arg(short = 'n', long, default_value_t = 20)]
Expand Down Expand Up @@ -230,6 +236,38 @@ fn real_main(cli: Cli) -> Result<()> {
let m = snap(&root, &store, Trigger::Manual { label: message })?;
println!("snapshot #{} ({} files)", m.id, m.entries.len());
}
Cmd::Pin { id } => {
let _l = store.lock()?;
if store.set_pinned(id, true)? {
println!("pinned snapshot #{id}");
} else {
println!("snapshot #{id} is already pinned");
}
}
Cmd::Unpin { id } => {
let _l = store.lock()?;
if store.set_pinned(id, false)? {
println!("unpinned snapshot #{id}");
} else {
println!("snapshot #{id} was not pinned");
}
}
Cmd::Pinned => {
let ids = store.pinned()?;
if ids.is_empty() {
println!("no pinned snapshots");
} else {
for id in ids {
let m = store.read_manifest(id)?;
println!(
"#{:<5} {:>4} files {}",
id,
m.entries.len(),
m.trigger.label()
);
}
}
}
Cmd::Log { limit } => log(&store, limit)?,
Cmd::Diff { from, to, patch } => {
let from_id = match from {
Expand Down
Loading