Skip to content

The agent that grows with you

fix(checkpoints): a checkpoint never waits on git gc; the periodic prune reclaims

ethernet8ec89a508884
diff --git a/tests/tools/test_checkpoint_size_cap.py b/tests/tools/test_checkpoint_size_cap.py
index 06f113956fc..b19d473928a 100644
--- a/tests/tools/test_checkpoint_size_cap.py
+++ b/tests/tools/test_checkpoint_size_cap.py
@@ -27,22 +27,48 @@ def history(tmp_path, monkeypatch):
return base, project, manager
[email protected]("entry", ["maintenance", "snapshot"])
-def test_size_cap_retains_every_snapshot_after_the_only_large_one(history, entry):
+def test_maintenance_size_cap_retains_every_snapshot_after_the_only_large_one(history):
base, project, manager = history
store = checkpoints._store_path(base)
assert checkpoints._dir_size_bytes(store) > 1024 * 1024
- expected = [f"small-{index}" for index in reversed(range(5))]
- if entry == "maintenance":
- result = checkpoints.prune_checkpoints(retention_days=0, checkpoint_base=base, max_total_size_mb=1)
- assert result["errors"] == 0
- else:
- manager.max_total_size_mb = 1
- (project / "new.txt").write_text("new snapshot", encoding="utf-8")
- manager.new_turn()
+ result = checkpoints.prune_checkpoints(retention_days=0, checkpoint_base=base, max_total_size_mb=1)
+ assert result["errors"] == 0
+ assert [row["reason"] for row in manager.list_checkpoints(str(project))] == [f"small-{i}" for i in reversed(range(5))]
+ assert checkpoints._dir_size_bytes(store) <= 1024 * 1024
+ assert (project / "small.txt").read_text(encoding="utf-8") == "4"
+
+
+def test_snapshot_over_cap_drops_one_round_and_leaves_the_gc_to_the_prune(history):
+ """A checkpoint never waits on ``git gc``: over the cap it rewrites the ref once and marks
+ the store gc-pending; the periodic prune reclaims the objects and clears the marker."""
+ from tools.checkpoint_pruning import GC_PENDING_NAME
+
+ base, project, manager = history
+ store = checkpoints._store_path(base)
+ manager.max_total_size_mb = 1
+ gc_calls = []
+ original = checkpoints._run_git
+
+ def count_gc(args, *rest, **kwargs):
+ if args[0] == "gc":
+ gc_calls.append(args)
+ return original(args, *rest, **kwargs)
+
+ (project / "new.txt").write_text("new snapshot", encoding="utf-8")
+ manager.new_turn()
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(checkpoints, "_run_git", count_gc)
assert manager.ensure_checkpoint(str(project), "newest")
- expected.insert(0, "newest")
- assert [row["reason"] for row in manager.list_checkpoints(str(project))] == expected
+ assert gc_calls == []
+ assert (store / GC_PENDING_NAME).exists()
+ assert [row["reason"] for row in manager.list_checkpoints(str(project))] == \
+ ["newest"] + [f"small-{i}" for i in reversed(range(5))]
+ # Objects are still in the pack until the prune runs.
+ assert checkpoints._dir_size_bytes(store) > 1024 * 1024
+
+ result = checkpoints.prune_checkpoints(retention_days=0, checkpoint_base=base, max_total_size_mb=1)
+ assert result["errors"] == 0
+ assert not (store / GC_PENDING_NAME).exists()
assert checkpoints._dir_size_bytes(store) <= 1024 * 1024
assert (project / "small.txt").read_text(encoding="utf-8") == "4"
@@ -98,7 +124,9 @@ def test_maintenance_stops_on_failed_git_without_losing_a_second_snapshot(histor
assert result["deleted_stale"] == 0
-def test_snapshot_pruning_does_not_enter_size_pass_after_failed_count_reclaim(history, monkeypatch, caplog):
+def test_snapshot_pruning_stops_at_a_failed_count_rewrite(history, monkeypatch, caplog):
+ """A count trim that cannot rewrite its ref aborts the take-path pruning before the size
+ round runs — never a partial history, never a second rewrite on top of a failed one."""
_, project, manager = history
manager.max_snapshots = 5
manager.max_total_size_mb = 1
@@ -107,19 +135,24 @@ def test_snapshot_pruning_does_not_enter_size_pass_after_failed_count_reclaim(hi
original = checkpoints._run_git
changed_refs = []
- def refuse_gc(args, *rest, **kwargs):
- if args[0] == "gc":
- return False, "", "injected reclamation failure"
+ def refuse_rewrite(args, *rest, **kwargs):
+ # The rewrite re-creates commits under their original dates; the snapshot's own
+ # commit-tree carries no extra_env.
+ if args[0] == "commit-tree" and kwargs.get("extra_env"):
+ return False, "", "injected rewrite failure"
result = original(args, *rest, **kwargs)
if args[0] == "update-ref" and result[0]:
changed_refs.append(args)
return result
- monkeypatch.setattr(checkpoints, "_run_git", refuse_gc)
+ monkeypatch.setattr(checkpoints, "_run_git", refuse_rewrite)
assert manager.ensure_checkpoint(str(project), "latest")
- assert len(changed_refs) == 2 # The new checkpoint plus one count trim.
- assert "injected reclamation failure" in caplog.text
- assert len(manager.list_checkpoints(str(project))) == 5
+ assert len(changed_refs) == 1 # The new checkpoint only; the trim failed before update-ref.
+ assert "injected rewrite failure" in caplog.text
+ store = checkpoints._store_path(checkpoints.CHECKPOINT_BASE)
+ ref = checkpoints._ref_name(checkpoints._project_hash(str(project)))
+ ok, out, _ = original(["rev-list", "--count", ref], store, str(project))
+ assert ok and int(out) == 7 # Nothing trimmed: the failed rewrite left history whole.
def test_restore_keeps_its_target_alive_while_taking_the_safety_snapshot(history):
diff --git a/tools/checkpoint_manager.py b/tools/checkpoint_manager.py
index 11033d35cbb..2a295dcff64 100644
--- a/tools/checkpoint_manager.py
+++ b/tools/checkpoint_manager.py
@@ -1457,14 +1457,16 @@ class CheckpointManager:
)
def _prune(self, store: Path, working_dir: str, ref: str) -> None:
- """Apply both budgets through one checked pruning owner."""
+ """Checkpoint-take path: snapshot-count budget plus one size round, gc deferred to the
+ periodic prune — a repack here held the tool call for the whole gc on a large store."""
from tools.checkpoint_pruning import Pruner, PruneError
pruner = Pruner(_run_git, store, working_dir, _GIT_TIMEOUT, _dir_size_bytes, _REFS_PREFIX)
try:
pruner.trim(ref, self.max_snapshots)
- if not pruner.enforce_size(self.max_total_size_mb * 1024 * 1024):
- logger.warning("Checkpoint store remains over its size cap; minimum history retained")
+ if pruner.drop_one_round(self.max_total_size_mb * 1024 * 1024):
+ logger.info("Checkpoint store exceeded %d MB — dropped the oldest snapshot per project; "
+ "space is reclaimed by the next prune", self.max_total_size_mb)
except (PruneError, OSError) as exc:
logger.warning("Checkpoint pruning stopped: %s", exc)
@@ -1835,7 +1837,8 @@ def _prune_checkpoints(
pruner = Pruner(_run_git, store, str(base), _GIT_TIMEOUT, _dir_size_bytes, _REFS_PREFIX)
try:
- pruner.reclaim()
+ if result["deleted_orphan"] + result["deleted_stale"] or pruner.gc_pending():
+ pruner.reclaim()
if not pruner.enforce_size(max_total_size_mb * 1024 * 1024):
result["errors"] += 1
logger.warning("Checkpoint store remains over its size cap; minimum history retained")
@@ -2091,7 +2094,9 @@ def clear_legacy(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
out["bytes_freed"] += size
out["deleted"] += 1
except OSError as exc:
+ out["errors"] += 1
logger.warning("Could not delete legacy archive %s: %s", child, exc)
except (OSError, RuntimeError) as exc:
+ out["errors"] += 1
logger.warning("Could not clear legacy archives: %s", exc)
return out
diff --git a/tools/checkpoint_pruning.py b/tools/checkpoint_pruning.py
index 9c03fa1c92d..889e4bf0d8a 100644
--- a/tools/checkpoint_pruning.py
+++ b/tools/checkpoint_pruning.py
@@ -12,6 +12,9 @@ class PruneError(RuntimeError):
"""Pruning stopped without permission to discard another snapshot."""
+GC_PENDING_NAME = ".gc-pending"
+
+
def store_lock_path(base: Path) -> Path:
base = base.resolve()
return base.with_name(f".{base.name}.lock")
@@ -49,11 +52,26 @@ class Pruner:
return output
def reclaim(self) -> None:
+ """Full ``git gc`` — tens of seconds on a GB store, so only the periodic prune calls it.
+ A ref rewrite that ran without it leaves a marker so the next prune reclaims."""
self._git(["reflog", "expire", "--expire=now", "--all"])
self._git(["gc", "--prune=now", "--quiet"], timeout=self.timeout * 3)
# Bare stores must remain usable when gc packs all refs.
for name in ("refs/heads", "branches"):
(self.store / name).mkdir(parents=True, exist_ok=True)
+ try:
+ (self.store / GC_PENDING_NAME).unlink()
+ except OSError:
+ pass
+
+ def gc_pending(self) -> bool:
+ return (self.store / GC_PENDING_NAME).exists()
+
+ def _mark_gc_pending(self) -> None:
+ try:
+ (self.store / GC_PENDING_NAME).touch()
+ except OSError:
+ pass
def _commits(self, ref: str) -> list[str]:
commits = self._git(["rev-list", "--reverse", ref]).splitlines()
@@ -61,7 +79,7 @@ class Pruner:
raise PruneError(f"checkpoint ref has no readable history: {ref}")
return commits
- def _rewrite(self, ref: str, original: list[str], keep: list[str]) -> None:
+ def _rewrite(self, ref: str, original: list[str], keep: list[str], *, gc: bool) -> None:
parent = None
for sha in keep:
metadata = self._git(["log", "-1", "--format=%T%x00%aI%x00%cI%x00%s", sha])
@@ -79,16 +97,35 @@ class Pruner:
raise PruneError("cannot remove a project's last snapshot")
# Never overwrite a snapshot published since we read this history.
self._git(["update-ref", ref, parent, original[-1]])
- self.reclaim()
+ if gc:
+ self.reclaim()
+ else:
+ self._mark_gc_pending()
def trim(self, ref: str, keep_count: int) -> None:
+ """Snapshot-count budget on the checkpoint-take path: rewrites the ref, defers the gc."""
commits = self._commits(ref)
keep_count = max(1, keep_count)
if len(commits) > keep_count:
- self._rewrite(ref, commits, commits[-keep_count:])
+ self._rewrite(ref, commits, commits[-keep_count:], gc=False)
+
+ def drop_one_round(self, cap_bytes: int) -> bool:
+ """Over the cap on the take path: drop the oldest snapshot of every project once and
+ defer the gc. One round per checkpoint converges over turns; the full loop measured
+ against an unchanging pack once flattened every project to a single snapshot."""
+ if cap_bytes <= 0 or self.dir_size(self.store) <= cap_bytes:
+ return False
+ changed = False
+ for ref in self._git(["for-each-ref", "--format=%(refname)", self.refs_prefix]).splitlines():
+ commits = self._commits(ref)
+ if len(commits) > 1:
+ self._rewrite(ref, commits, commits[1:], gc=False)
+ changed = True
+ return changed
def enforce_size(self, cap_bytes: int) -> bool:
- """Return whether the cap fits; a failed Git step raises immediately."""
+ """Periodic prune: gc per round (the measurement only moves after a repack) until the
+ store fits. Returns whether it did; a failed Git step raises immediately."""
if cap_bytes <= 0 or self.dir_size(self.store) <= cap_bytes:
return True
self.reclaim()
@@ -103,7 +140,7 @@ class Pruner:
commits = self._commits(ref)
if len(commits) <= 1:
continue
- self._rewrite(ref, commits, commits[1:])
+ self._rewrite(ref, commits, commits[1:], gc=True)
changed = True
if self.dir_size(self.store) <= cap_bytes:
return True