fix: rewind allocator when pruning future
This commit is contained in:
parent
c52bc49d05
commit
f3a5aa0d58
|
|
@ -44,7 +44,8 @@ tests open it as a real repository and validate its map and world invariants.
|
|||
**History semantics checkpoint: complete.** `revert` now defaults to a
|
||||
reviewable worktree inverse, `revert --commit` warns before adding history, and
|
||||
`reset --hard` provides a previewed, explicitly confirmed destructive rewind.
|
||||
Recoverable future pruning remains the recommended alternative.
|
||||
Recoverable future pruning remains the recommended alternative and rewinds the
|
||||
next epoch to `HEAD + 1`, with allocator and tags included in its backup.
|
||||
|
||||
## Phase 0 — audit and guardrails
|
||||
|
||||
|
|
|
|||
|
|
@ -187,7 +187,7 @@ fn resolve(workspace: &Workspace, identifier: &EpochIdentifier) -> Result<EpochI
|
|||
|
||||
/// Move future epochs into a recoverable backup, or restore that backup.
|
||||
pub fn prune_future(command: &PruneFutureCmd) -> Result<(), AppError> {
|
||||
let workspace = Workspace::open(Path::new("."))?;
|
||||
let mut workspace = Workspace::open(Path::new("."))?;
|
||||
if let Some(backup) = &command.restore {
|
||||
if !command.yes {
|
||||
println!("Restore preview: {}", backup.display());
|
||||
|
|
|
|||
|
|
@ -214,6 +214,10 @@ fn native_staging_commit_restore_and_recovery_workflow() {
|
|||
assert!(stdout(&preview).contains("1 epoch(s)"));
|
||||
assert_success(&efo(&repo, &["prune-future", "--yes"]));
|
||||
assert!(!repo.path().join("epoch/2").exists());
|
||||
let pruned_manifest: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(repo.path().join(".epoch")).expect("pruned manifest"))
|
||||
.expect("parse pruned manifest");
|
||||
assert_eq!(pruned_manifest["next_epoch_id"]["id"], 2);
|
||||
let prune_root = repo.path().join(".efo/pruned");
|
||||
let backup = fs::read_dir(&prune_root)
|
||||
.expect("prune backups")
|
||||
|
|
@ -231,6 +235,10 @@ fn native_staging_commit_restore_and_recovery_workflow() {
|
|||
],
|
||||
));
|
||||
assert!(repo.path().join("epoch/2/epochinfo.json").exists());
|
||||
let restored_manifest: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(repo.path().join(".epoch")).expect("restored manifest"))
|
||||
.expect("parse restored manifest");
|
||||
assert_eq!(restored_manifest["next_epoch_id"]["id"], 3);
|
||||
|
||||
let recovery = efo(&repo, &["recover"]);
|
||||
assert_success(&recovery);
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ parent directories. `efo <command> --help` is the authoritative syntax.
|
|||
- `efo epoch fsck` performs a read-only consistency check of epoch IDs, tags,
|
||||
and entity UUIDs. It does not repair damage.
|
||||
- `efo prune-future` previews later history; `--yes` moves it to a restorable
|
||||
backup.
|
||||
backup, removes tags into that future, and makes the next commit use the ID
|
||||
immediately after HEAD. Restoring the backup restores its allocator and tags.
|
||||
- `efo reset --hard ID_OR_TAG` previews a destructive rewind. Add `--yes` to
|
||||
align HEAD, index, and worktree to the target and permanently delete every
|
||||
newer epoch. This has no built-in undo; prefer `switch` plus `prune-future`
|
||||
|
|
@ -66,7 +67,9 @@ review; it can be undone with `restore --worktree --all`. `revert ID --commit`
|
|||
prints a warning and immediately creates the inverse commit. Overlap with later
|
||||
changes aborts without mutation. `efo prune-future` previews future epochs,
|
||||
while `--yes` moves them into a backup. Restore using the exact command printed
|
||||
after pruning. `efo reset --hard ID --yes` is the explicitly destructive
|
||||
after pruning; this also restores the former next-epoch allocator and tags.
|
||||
After pruning, new linear history begins at `HEAD + 1` rather than retaining a
|
||||
gap for the removed epochs. `efo reset --hard ID --yes` is the explicitly destructive
|
||||
alternative: it discards transient changes, removes newer epochs without a
|
||||
backup, removes tags that point to them, and restarts the epoch allocator after
|
||||
the retained target.
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ efo restore --staged --all # unstage everything
|
|||
| `revert ID` | `restore --worktree --all` | Restore from Git/backup |
|
||||
| `revert ID --commit` | Revert the inverse commit | Restore from Git/backup |
|
||||
| `switch` | Switch back to the previous ID/tag | Not applicable |
|
||||
| `prune-future --yes` | Use the printed `prune-future --restore … --yes` command | Not applicable |
|
||||
| `prune-future --yes` | Use the printed `prune-future --restore … --yes` command; epochs, tags, and allocator are restored | Not applicable |
|
||||
| `reset --hard ID --yes` | None | Restore the complete repository from Git/backup |
|
||||
|
||||
Before a hard reset, preserve the complete repository—not only the current
|
||||
|
|
|
|||
|
|
@ -38,7 +38,9 @@ which layer it replaces. IDs are monotonic and never reused.
|
|||
places an inverse change in the worktree by default; `--commit` explicitly
|
||||
creates a new inverse commit and warns before doing so. `efo prune-future`
|
||||
previews later epochs and, with confirmation, moves them into a restorable
|
||||
backup rather than deleting them.
|
||||
backup rather than deleting them. Pruning removes future-pointing tags and
|
||||
rewinds the allocator to `HEAD + 1`; its backup records both so restoration
|
||||
reconstructs the original timeline metadata.
|
||||
|
||||
`efo reset --hard TARGET --yes` is the exceptional destructive path. It resets
|
||||
HEAD, index, and worktree, permanently deletes all newer epoch directories,
|
||||
|
|
|
|||
|
|
@ -78,8 +78,9 @@ reinforce meaning, but never carry meaning alone.
|
|||
being moved backward. It never deletes history. Conflicts abort without
|
||||
changing any layer and list affected fields.
|
||||
- `efo prune-future` is the recoverable history-removal operation. It always
|
||||
shows a dry-run, requires `--yes`, never rewinds the ID allocator, and leaves
|
||||
a backup that can be restored.
|
||||
shows a dry-run, requires `--yes`, rewinds the ID allocator to the first free
|
||||
ID after HEAD, and leaves a backup containing the epochs, prior allocator,
|
||||
and removed tags so the complete future can be restored.
|
||||
- `efo reset --hard <epoch>` is a separate, deliberately destructive escape
|
||||
hatch modelled after Git. It previews by default and requires `--yes` to
|
||||
discard transient state, move HEAD, delete newer epochs and their tags, and
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use std::{
|
|||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
|
|
@ -15,9 +15,20 @@ use crate::{
|
|||
epoch::EpochInfo,
|
||||
repository_format::{FormatError, RepositoryManifest, RepositorySnapshot, decode_manifest},
|
||||
stats::EntityType,
|
||||
transaction::{TransactionError, replace_file, replace_files},
|
||||
transaction::{
|
||||
RepositoryLock, TransactionError, replace_file, replace_files, replace_files_locked,
|
||||
},
|
||||
};
|
||||
|
||||
/// Manifest state removed alongside a recoverable future-history prune.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct PruneMetadata {
|
||||
/// Allocator value to restore when no replacement history was created.
|
||||
next_epoch_id: crate::epoch::EpochId,
|
||||
/// Tags whose targets were moved into the prune backup.
|
||||
removed_tags: BTreeMap<String, crate::epoch::EpochId>,
|
||||
}
|
||||
|
||||
/// A validated repository and its three state layers.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Workspace {
|
||||
|
|
@ -589,7 +600,7 @@ impl Workspace {
|
|||
}
|
||||
|
||||
/// Move future snapshots into a recoverable backup directory.
|
||||
pub fn prune_future(&self) -> Result<PathBuf, WorkspaceError> {
|
||||
pub fn prune_future(&mut self) -> Result<PathBuf, WorkspaceError> {
|
||||
if self.has_staged_changes() || self.has_unstaged_changes() {
|
||||
return Err(WorkspaceError::Dirty);
|
||||
}
|
||||
|
|
@ -598,25 +609,67 @@ impl Workspace {
|
|||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|_| WorkspaceError::Inconsistent("system clock is before Unix epoch".into()))?
|
||||
.as_secs();
|
||||
let backup = self.root.join(format!(".efo/pruned/{stamp}/epoch"));
|
||||
let backup_root = self.root.join(format!(".efo/pruned/{stamp}"));
|
||||
let backup = backup_root.join("epoch");
|
||||
fs::create_dir_all(&backup).map_err(|source| io(&backup, source))?;
|
||||
let _lock = crate::transaction::RepositoryLock::acquire(&self.root, "prune-future")?;
|
||||
for id in ids {
|
||||
let removed_tags = self
|
||||
.manifest
|
||||
.tags
|
||||
.iter()
|
||||
.filter(|(_, id)| ids.contains(id))
|
||||
.map(|(name, id)| (name.clone(), *id))
|
||||
.collect();
|
||||
let metadata = PruneMetadata {
|
||||
next_epoch_id: self.manifest.next_epoch_id,
|
||||
removed_tags,
|
||||
};
|
||||
let metadata_path = backup_root.join("prune.json");
|
||||
let lock = RepositoryLock::acquire(&self.root, "prune-future")?;
|
||||
replace_files_locked(
|
||||
&self.root,
|
||||
&[(metadata_path, encode(&metadata, "prune metadata")?)],
|
||||
&lock,
|
||||
)?;
|
||||
for id in &ids {
|
||||
let source = self.root.join(format!("epoch/{id}"));
|
||||
let destination = backup.join(id.to_string());
|
||||
fs::rename(&source, &destination).map_err(|source_error| io(&source, source_error))?;
|
||||
}
|
||||
Ok(backup.parent().unwrap_or(&backup).to_path_buf())
|
||||
let mut manifest = self.manifest.clone();
|
||||
manifest.next_epoch_id = crate::epoch::EpochId::new(manifest.epoch_id.id + 1);
|
||||
manifest.tags.retain(|_, id| !ids.contains(id));
|
||||
replace_files_locked(
|
||||
&self.root,
|
||||
&[(self.root.join(".epoch"), encode(&manifest, "manifest")?)],
|
||||
&lock,
|
||||
)?;
|
||||
self.manifest = manifest;
|
||||
Ok(backup_root)
|
||||
}
|
||||
|
||||
/// Restore all epoch directories from a prune backup.
|
||||
pub fn restore_pruned(&self, backup: &Path) -> Result<usize, WorkspaceError> {
|
||||
pub fn restore_pruned(&mut self, backup: &Path) -> Result<usize, WorkspaceError> {
|
||||
let epoch_backup = backup.join("epoch");
|
||||
let _lock =
|
||||
crate::transaction::RepositoryLock::acquire(&self.root, "restore pruned history")?;
|
||||
let mut restored = 0;
|
||||
for entry in fs::read_dir(&epoch_backup).map_err(|source| io(&epoch_backup, source))? {
|
||||
let entry = entry.map_err(|source| io(&epoch_backup, source))?;
|
||||
let metadata_path = backup.join("prune.json");
|
||||
let metadata = if metadata_path.is_file() {
|
||||
Some(decode::<PruneMetadata>(&metadata_path)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(metadata) = &metadata {
|
||||
for name in metadata.removed_tags.keys() {
|
||||
if self.manifest.tags.contains_key(name) {
|
||||
return Err(WorkspaceError::Inconsistent(format!(
|
||||
"cannot restore tag `{name}` because it already exists"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let entries = fs::read_dir(&epoch_backup)
|
||||
.map_err(|source| io(&epoch_backup, source))?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|source| io(&epoch_backup, source))?;
|
||||
for entry in &entries {
|
||||
let destination = self.root.join("epoch").join(entry.file_name());
|
||||
if destination.exists() {
|
||||
return Err(WorkspaceError::Inconsistent(format!(
|
||||
|
|
@ -624,9 +677,29 @@ impl Workspace {
|
|||
destination.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
let lock = RepositoryLock::acquire(&self.root, "restore pruned history")?;
|
||||
let mut restored = 0;
|
||||
for entry in entries {
|
||||
let destination = self.root.join("epoch").join(entry.file_name());
|
||||
fs::rename(entry.path(), &destination).map_err(|source| io(&destination, source))?;
|
||||
restored += 1;
|
||||
}
|
||||
let mut manifest = self.manifest.clone();
|
||||
if let Some(metadata) = metadata {
|
||||
manifest.next_epoch_id = manifest.next_epoch_id.max(metadata.next_epoch_id);
|
||||
for (name, id) in metadata.removed_tags {
|
||||
manifest.tags.insert(name, id);
|
||||
}
|
||||
} else if let Some(last) = self.all_epoch_ids()?.last() {
|
||||
manifest.next_epoch_id = crate::epoch::EpochId::new(last.id + 1);
|
||||
}
|
||||
replace_files_locked(
|
||||
&self.root,
|
||||
&[(self.root.join(".epoch"), encode(&manifest, "manifest")?)],
|
||||
&lock,
|
||||
)?;
|
||||
self.manifest = manifest;
|
||||
Ok(restored)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -119,11 +119,14 @@ fn commit_creates_immutable_history_and_advances_all_layers() {
|
|||
);
|
||||
let backup = workspace.prune_future().expect("prune future");
|
||||
assert!(!directory.path().join("epoch/2").exists());
|
||||
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(2));
|
||||
assert!(backup.join("prune.json").is_file());
|
||||
assert_eq!(
|
||||
workspace.restore_pruned(&backup).expect("restore future"),
|
||||
1
|
||||
);
|
||||
assert!(directory.path().join("epoch/2/epochinfo.json").exists());
|
||||
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -191,3 +194,29 @@ fn hard_reset_discards_transient_state_and_newer_epochs() {
|
|||
assert!(workspace.worktree.world.summary.is_empty());
|
||||
assert!(!directory.path().join("epoch/1").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_backup_restores_future_tags_and_allocator() {
|
||||
let directory = repository();
|
||||
let mut workspace = Workspace::open(directory.path()).expect("workspace");
|
||||
workspace.worktree.world.summary = "tagged future".into();
|
||||
workspace.worktree.world.tags.push("future".into());
|
||||
workspace.stage_all().expect("stage tagged future");
|
||||
workspace
|
||||
.commit("Tagged future".into())
|
||||
.expect("commit future");
|
||||
workspace.switch(EpochId::new(0)).expect("switch backward");
|
||||
|
||||
let backup = workspace.prune_future().expect("prune tagged future");
|
||||
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(1));
|
||||
assert!(!workspace.manifest.tags.contains_key("future"));
|
||||
|
||||
workspace
|
||||
.restore_pruned(&backup)
|
||||
.expect("restore tagged future");
|
||||
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(2));
|
||||
assert_eq!(
|
||||
workspace.manifest.tags.get("future"),
|
||||
Some(&EpochId::new(1))
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue