Skip to content

Commit fc1119c

Browse files
MaxFreedomPollardteknium1
authored andcommitted
fix(curator): stop the rollback safety snapshot from pruning its target
Rolling back to the oldest curator snapshot failed and deleted that snapshot. rollback() takes a safety snapshot first, and snapshot_skills() ends by pruning the backups directory down to keep (5 by default). At the steady keep limit that prune removed the oldest snapshot, which is the very one being restored, so the extract found no skills.tar.gz and the rollback stopped with "snapshot extract failed (state restored)". Thread an optional protect set through snapshot_skills() into _prune_old() so the pre rollback safety snapshot can never evict the snapshot being restored. Add two regression tests covering restore of the oldest snapshot at the keep limit. Fixes #47612
1 parent 7bbffce commit fc1119c

2 files changed

Lines changed: 82 additions & 7 deletions

File tree

‎agent/curator_backup.py‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
import tarfile
4747
from datetime import datetime, timezone
4848
from pathlib import Path
49-
from typing import Any, Dict, List, Optional, Tuple
49+
from typing import Any, Dict, List, Optional, Set, Tuple
5050

5151
from hermes_constants import get_hermes_home
5252
from agent.skill_utils import is_excluded_skill_path
@@ -208,13 +208,17 @@ def _write_manifest(dest: Path, reason: str, archive_path: Path,
208208
)
209209

210210

211-
def snapshot_skills(reason: str = "manual") -> Optional[Path]:
211+
def snapshot_skills(reason: str = "manual", *, protect_ids: Optional[Set[str]] = None) -> Optional[Path]:
212212
"""Create a tar.gz snapshot of ``~/.hermes/skills/`` and prune old ones.
213213
214214
Returns the snapshot directory path, or ``None`` if the snapshot was
215215
skipped (backup disabled, skills dir missing, or an IO error occurred —
216216
in which case we log at debug and return None so the curator never
217217
aborts a pass because of a backup failure).
218+
219+
``protect_ids`` is forwarded to the prune step so callers can guarantee
220+
specific snapshot ids survive even when they fall outside the keep
221+
window (rollback passes the id it is about to restore from).
218222
"""
219223
if not is_enabled():
220224
logger.debug("Curator backup disabled by config; skipping snapshot")
@@ -276,15 +280,19 @@ def snapshot_skills(reason: str = "manual") -> Optional[Path]:
276280
pass
277281
return None
278282

279-
_prune_old(keep=get_keep())
283+
_prune_old(keep=get_keep(), protect=protect_ids)
280284
logger.info("Curator snapshot created: %s (%s)", snap_id, reason)
281285
return dest
282286

283287

284-
def _prune_old(keep: int) -> List[str]:
288+
def _prune_old(keep: int, protect: Optional[Set[str]] = None) -> List[str]:
285289
"""Delete regular snapshots beyond the newest *keep*. Returns deleted
286-
ids. Staging dirs (``.rollback-staging-*``) are implementation detail
287-
and pruned independently on every call."""
290+
ids. Snapshot ids in *protect* are never deleted even when they fall
291+
outside the keep window — rollback() uses this so the mandatory
292+
pre-rollback safety snapshot can never evict the very snapshot being
293+
restored. Staging dirs (``.rollback-staging-*``) are implementation
294+
detail and pruned independently on every call."""
295+
protect = protect or set()
288296
backups = _backups_dir()
289297
if not backups.exists():
290298
return []
@@ -305,6 +313,8 @@ def _prune_old(keep: int) -> List[str]:
305313
entries.sort(key=lambda t: t[0], reverse=True)
306314
deleted: List[str] = []
307315
for _, path in entries[keep:]:
316+
if path.name in protect:
317+
continue
308318
try:
309319
shutil.rmtree(path)
310320
deleted.append(path.name)
@@ -564,7 +574,13 @@ def rollback(backup_id: Optional[str] = None) -> Tuple[bool, str, Optional[Path]
564574
# out before touching anything — otherwise a failed extract could leave
565575
# the user with no skills.
566576
try:
567-
snapshot_skills(reason=f"pre-rollback to {target.name}")
577+
# Protect the target from this snapshot's prune step: at the steady
578+
# keep limit, pruning the oldest snapshot would otherwise delete the
579+
# very snapshot we are about to extract from.
580+
snapshot_skills(
581+
reason=f"pre-rollback to {target.name}",
582+
protect_ids={target.name},
583+
)
568584
except Exception as e:
569585
return (False, f"pre-rollback safety snapshot failed: {e}", None)
570586

‎tests/agent/test_curator_backup.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,3 +592,62 @@ def test_restore_cron_skill_links_standalone(backup_env):
592592
assert report["restored"][0]["to"]["skills"] == ["narrow-a", "narrow-b"]
593593
assert len(report["skipped_missing"]) == 1
594594
assert report["skipped_missing"][0]["job_id"] == "job-gone"
595+
596+
597+
# ---------------------------------------------------------------------------
598+
# Rollback must not let the pre-rollback safety snapshot prune the target
599+
# (regression: restoring the oldest snapshot at the keep limit destroyed it)
600+
# ---------------------------------------------------------------------------
601+
602+
def _three_ordered_snapshots(cb, skills, monkeypatch):
603+
"""Create snapshots 05-01 / 05-02 / 05-03 capturing growing trees, with
604+
keep=3 so the backups dir is exactly at the retention limit. 05-01 holds
605+
only 'pristine'; later snapshots add 'extra2' and 'extra3'. Leaves
606+
_utc_id patched to a newest id so the rollback safety snapshot sorts
607+
last. Returns the oldest snapshot id."""
608+
monkeypatch.setattr(cb, "get_keep", lambda: 3)
609+
plan = [
610+
("2026-05-01T00-00-00Z", ["pristine"]),
611+
("2026-05-02T00-00-00Z", ["pristine", "extra2"]),
612+
("2026-05-03T00-00-00Z", ["pristine", "extra2", "extra3"]),
613+
]
614+
for snap_id, names in plan:
615+
for n in names:
616+
_write_skill(skills, n)
617+
monkeypatch.setattr(cb, "_utc_id", lambda now=None, _i=snap_id: _i)
618+
assert cb.snapshot_skills(reason=snap_id) is not None
619+
monkeypatch.setattr(cb, "_utc_id", lambda now=None: "2026-05-09T00-00-00Z")
620+
return "2026-05-01T00-00-00Z"
621+
622+
623+
def test_rollback_to_oldest_snapshot_at_keep_limit_succeeds(backup_env, monkeypatch):
624+
"""Restoring the oldest snapshot when the backups dir is at the keep limit
625+
must succeed: the pre-rollback safety snapshot's prune step must not evict
626+
the snapshot being restored."""
627+
cb = backup_env["cb"]
628+
skills = backup_env["skills"]
629+
oldest = _three_ordered_snapshots(cb, skills, monkeypatch)
630+
631+
ok, msg, _ = cb.rollback(backup_id=oldest)
632+
633+
assert ok is True, f"rollback to oldest snapshot should succeed, got: {msg}"
634+
# 05-01 only contained 'pristine'; a real restore reflects exactly that.
635+
assert (skills / "pristine" / "SKILL.md").exists()
636+
assert not (skills / "extra3").exists(), "tree was not restored to the oldest snapshot"
637+
638+
639+
def test_rollback_does_not_delete_the_snapshot_it_restores_from(backup_env, monkeypatch):
640+
"""The snapshot a rollback restores from must still exist afterwards — the
641+
safety snapshot's prune must never delete the target."""
642+
cb = backup_env["cb"]
643+
skills = backup_env["skills"]
644+
oldest = _three_ordered_snapshots(cb, skills, monkeypatch)
645+
target_dir = skills / ".curator_backups" / oldest
646+
assert target_dir.exists(), "precondition: target snapshot exists before rollback"
647+
648+
cb.rollback(backup_id=oldest)
649+
650+
assert target_dir.exists(), (
651+
"the pre-rollback safety snapshot pruned away the snapshot being "
652+
"restored — the oldest restore point is destroyed by restoring to it"
653+
)

0 commit comments

Comments
 (0)