Skip to content
Open
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
55 changes: 55 additions & 0 deletions tests/tools/test_checkpoint_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
_run_git,
_git_env,
_dir_file_count,
_clear_stale_lock,
_STALE_LOCK_SECONDS,
format_checkpoint_list,
DEFAULT_EXCLUDES,
CHECKPOINT_BASE,
Expand Down Expand Up @@ -597,6 +599,7 @@ def test_restore_accepts_valid_file_path(self, mgr, work_dir):
# every time the agent took a background snapshot.

import os as _os
import time as _time


class TestGpgAndGlobalConfigIsolation:
Expand Down Expand Up @@ -696,3 +699,55 @@ def test_checkpoint_works_on_prefix_shadow_without_local_gpgsign(
mgr = CheckpointManager(enabled=True)
assert mgr.ensure_checkpoint(str(work_dir), reason="prefix-shadow") is True
assert len(mgr.list_checkpoints(str(work_dir))) == 1


class TestStaleLockCleanup:
"""Stale index.lock cleanup prevents wedged checkpoints after a crashed
git process leaves a zombie lock file (observed in production: 56+ errors
over 6 days on one shadow repo)."""

def _backdate(self, path, seconds_ago):
ts = _time.time() - seconds_ago
_os.utime(path, (ts, ts))

def test_removes_old_stale_lock(self, tmp_path):
shadow = tmp_path / "shadow"
shadow.mkdir()
lock = shadow / "index.lock"
lock.touch()
self._backdate(lock, _STALE_LOCK_SECONDS + 30)
_clear_stale_lock(shadow)
assert not lock.exists()

def test_preserves_fresh_lock(self, tmp_path):
"""A lock younger than the threshold may belong to a live git op —
leave it alone."""
shadow = tmp_path / "shadow"
shadow.mkdir()
lock = shadow / "index.lock"
lock.touch()
_clear_stale_lock(shadow)
assert lock.exists()

def test_noop_when_no_lock(self, tmp_path):
shadow = tmp_path / "shadow"
shadow.mkdir()
_clear_stale_lock(shadow) # must not raise

def test_run_git_unwedges_after_stale_lock(
self, work_dir, checkpoint_base, monkeypatch
):
"""End-to-end: a stale lock predating a real git call is cleaned up
automatically, and the call succeeds."""
monkeypatch.setattr("tools.checkpoint_manager.CHECKPOINT_BASE", checkpoint_base)
shadow = _shadow_repo_path(str(work_dir))
_init_shadow_repo(shadow, str(work_dir))

stale = shadow / "index.lock"
stale.touch()
self._backdate(stale, _STALE_LOCK_SECONDS + 30)

ok, _, _ = _run_git(["add", "-A"], shadow, str(work_dir))
assert ok, "git add -A should succeed after stale-lock cleanup"
assert not stale.exists()

35 changes: 35 additions & 0 deletions tools/checkpoint_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import re
import shutil
import subprocess
import time
from pathlib import Path
from hermes_constants import get_hermes_home
from typing import Dict, List, Optional, Set
Expand Down Expand Up @@ -159,6 +160,38 @@ def _git_env(shadow_repo: Path, working_dir: str) -> dict:
return env


_STALE_LOCK_SECONDS = 60.0


def _clear_stale_lock(shadow_repo: Path) -> None:
"""Remove a stale ``index.lock`` left behind by a crashed/killed git process.

Checkpoint ops against a shadow repo are strictly serial (one gateway
agent per session), so any ``index.lock`` older than ``_STALE_LOCK_SECONDS``
at entry to a new git call is unambiguously orphaned. Without this,
a single crashed ``git add`` wedges checkpointing for that repo until
manual cleanup (seen in logs: 56+ errors over 6 days on one shadow).
"""
lock_path = shadow_repo / "index.lock"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current main no longer stages through a per-shadow-repo root index: _take() passes store/indexes/<project-hash> as GIT_INDEX_FILE. This should target the lock associated with the actual index_file, otherwise a stale lock from the active git add path remains untouched.

try:
age = time.time() - lock_path.stat().st_mtime
except FileNotFoundError:
return
except OSError:
return
if age < _STALE_LOCK_SECONDS:
return
try:
lock_path.unlink()
logger.warning(
"Removed stale index.lock (age=%.0fs) at %s", age, lock_path,
)
except FileNotFoundError:
pass
except OSError as exc:
logger.warning("Failed to remove stale index.lock at %s: %s", lock_path, exc)


def _run_git(
args: List[str],
shadow_repo: Path,
Expand All @@ -182,6 +215,8 @@ def _run_git(
logger.error("Git command skipped: %s (%s)", " ".join(["git"] + list(args)), msg)
return False, "", msg

_clear_stale_lock(shadow_repo)

env = _git_env(shadow_repo, str(normalized_working_dir))
cmd = ["git"] + list(args)
allowed_returncodes = allowed_returncodes or set()
Expand Down