Skip to content

The agent that grows with you

fix(state): make backup atomic and the disk guard proportional

jirathip-kc914a9ac4be6
diff --git a/hermes_state.py b/hermes_state.py
index ca78943f9e7..cad93e95c84 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1859,12 +1859,27 @@ _MAX_MALFORMED_BACKUPS = 3
# header on any real recovery), while staying O(1) on a multi-GB file.
_FINGERPRINT_SAMPLE_BYTES = 65536
-# Free-space floor for the pre-repair forensic backup. The backup is a full
-# raw copy of the damaged DB, so a repair loop on a large state.db is a disk
-# amplifier: the reported incident wrote 98MB every ~10s until the volume was
-# nearly full, which would have taken down every agent on the host. Refuse
-# the copy unless the volume would still hold this much afterwards.
-_REPAIR_BACKUP_MIN_FREE_BYTES = 2 * 1024 * 1024 * 1024 # 2 GiB
+# Free-space headroom for the pre-repair forensic backup. The backup is a
+# full raw copy of the damaged DB (plus its -wal/-shm sidecars), so a repair
+# loop on a large state.db is a disk amplifier: the reporting incident wrote
+# ~98MB every ~10s until the volume was nearly full, which would have taken
+# down every agent on the host.
+#
+# Proportional, not a flat floor: an absolute multi-GB reserve would refuse
+# backups that fit comfortably on small container/VM volumes, and because a
+# refused backup is a HARD STOP (#69603) that would silently convert "repair
+# loops" into "repair never runs" for those deployments. Require the copy
+# itself plus a small slice of the volume, clamped to a modest floor.
+_REPAIR_BACKUP_MIN_FREE_BYTES = 256 * 1024 * 1024 # 256 MiB absolute floor
+_REPAIR_BACKUP_FREE_FRACTION = 0.02 # plus 2% of the volume
+
+
+def _repair_backup_headroom_bytes(total_bytes: int) -> int:
+ """Free space required *beyond* the copy itself, for a volume of *total_bytes*."""
+ return max(
+ _REPAIR_BACKUP_MIN_FREE_BYTES,
+ int(total_bytes * _REPAIR_BACKUP_FREE_FRACTION),
+ )
def _repair_ledger_path(db_path: Path) -> Path:
@@ -2070,31 +2085,70 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":
return existing, None
except OSError:
pass
- # Disk guard: this is a full raw copy of a possibly multi-GB DB. On a
- # host whose volume is already nearly full — which a preceding repair
- # loop may itself have caused — taking it can finish off the disk and
- # take down every process on the machine. Refuse while there is still
- # room to refuse in.
+ # Disk guard: this is a full raw copy of a possibly multi-GB DB plus
+ # its sidecars. On a host whose volume is already nearly full — which
+ # a preceding repair loop may itself have caused — taking it can
+ # finish off the disk and take down every process on the machine.
+ # Refuse while there is still room to refuse in.
try:
- src_size = db_path.stat().st_size
- free = shutil.disk_usage(db_path.parent).free
- if free - src_size < _REPAIR_BACKUP_MIN_FREE_BYTES:
+ need = db_path.stat().st_size
+ for suffix in ("-wal", "-shm"):
+ sidecar = db_path.with_name(db_path.name + suffix)
+ if sidecar.exists():
+ need += sidecar.stat().st_size
+ usage = shutil.disk_usage(db_path.parent)
+ headroom = _repair_backup_headroom_bytes(usage.total)
+ if usage.free - need < headroom:
reason = (
- f"only {free / 1e9:.1f}GB free on {db_path.parent}; copying "
- f"the {src_size / 1e9:.1f}GB damaged DB would leave less than "
- f"{_REPAIR_BACKUP_MIN_FREE_BYTES / 1e9:.1f}GB. Free disk space, "
- "then retry (or recover manually with `sqlite3 "
- f"{db_path} \".recover\"`)."
+ f"only {usage.free / 1e9:.2f}GB free on {db_path.parent}; "
+ f"copying the damaged DB needs {need / 1e9:.2f}GB and must "
+ f"leave {headroom / 1e9:.2f}GB headroom. Free disk space, "
+ f"then retry (or recover manually with `sqlite3 {db_path} "
+ '".recover"`).'
)
logger.error("Refusing forensic backup of %s: %s", db_path, reason)
return None, reason
except OSError:
pass
- shutil.copy2(db_path, backup_path)
- for suffix in ("-wal", "-shm"):
- sidecar = db_path.with_name(db_path.name + suffix)
- if sidecar.exists():
- shutil.copy2(sidecar, backup_path.with_name(backup_path.name + suffix))
+ # Copy to a staging name that does NOT match the backup prefix, then
+ # rename into place only once every copy has succeeded. A copy that
+ # fails partway (ENOSPC, kill) would otherwise leave a prefix-matching
+ # partial that `_prune_malformed_backups` never reaches — prune runs
+ # only on the success path — so debris accumulated unbounded and, on a
+ # later successful pass, the newest-by-name partials were KEPT while
+ # intact forensic copies were pruned away.
+ staging = db_path.with_name(f"{backup_path.name}.incomplete")
+ staged: "List[Tuple[Path, Path]]" = []
+ try:
+ # Clear debris from an earlier interrupted pass (kill mid-copy).
+ # Matches sidecar staging names (``.incomplete-wal``) too.
+ for old in db_path.parent.glob(
+ f"{db_path.name}.malformed-backup-*.incomplete*"
+ ):
+ old.unlink(missing_ok=True)
+ shutil.copy2(db_path, staging)
+ staged.append((staging, backup_path))
+ for suffix in ("-wal", "-shm"):
+ sidecar = db_path.with_name(db_path.name + suffix)
+ if sidecar.exists():
+ side_staging = staging.with_name(staging.name + suffix)
+ shutil.copy2(sidecar, side_staging)
+ staged.append(
+ (side_staging, backup_path.with_name(backup_path.name + suffix))
+ )
+ for src, dst in staged:
+ os.replace(src, dst)
+ except Exception:
+ for src, _ in staged:
+ try:
+ src.unlink(missing_ok=True)
+ except OSError:
+ pass
+ try:
+ staging.unlink(missing_ok=True)
+ except OSError:
+ pass
+ raise
# Retention cap (#86747): keep only the newest few forensic copies.
_prune_malformed_backups(db_path)
return backup_path, None
diff --git a/tests/test_state_db_repair_loop_mtime.py b/tests/test_state_db_repair_loop_mtime.py
index 7a625d31f43..7fc4b23fa53 100644
--- a/tests/test_state_db_repair_loop_mtime.py
+++ b/tests/test_state_db_repair_loop_mtime.py
@@ -22,6 +22,7 @@ missing free-space refusal.
from __future__ import annotations
import os
+import shutil
import time
from pathlib import Path
from unittest.mock import patch
@@ -36,6 +37,7 @@ from hermes_state import (
_existing_malformed_backups,
_persistent_repair_attempts_exhausted,
_record_repair_outcome,
+ _repair_backup_headroom_bytes,
)
@@ -137,7 +139,9 @@ def test_backup_refused_when_disk_would_be_exhausted(tmp_path):
"""A nearly-full volume must not be finished off by the forensic copy."""
db = _damaged_db(tmp_path)
tight = type(
- "Usage", (), {"total": 0, "used": 0, "free": _REPAIR_BACKUP_MIN_FREE_BYTES // 2}
+ "Usage",
+ (),
+ {"total": 10_000_000_000, "used": 0, "free": _REPAIR_BACKUP_MIN_FREE_BYTES // 2},
)()
with patch("shutil.disk_usage", return_value=tight):
path, reason = _backup_db_file(db)
@@ -146,6 +150,79 @@ def test_backup_refused_when_disk_would_be_exhausted(tmp_path):
assert not _existing_malformed_backups(db)
+def test_backup_allowed_on_small_volume_with_room(tmp_path):
+ """A flat multi-GB floor would disable repair on small VMs/containers.
+
+ 50MB DB on a 10GB volume with 1.5GB free fits with ~30x headroom; the
+ guard must allow it rather than hard-stopping repair forever.
+ """
+ db = _damaged_db(tmp_path, size=50_000_000)
+ small_vm = type(
+ "Usage", (), {"total": 10_000_000_000, "used": 8_500_000_000, "free": 1_500_000_000}
+ )()
+ with patch("shutil.disk_usage", return_value=small_vm):
+ path, reason = _backup_db_file(db)
+ assert reason is None and path is not None
+
+
+def test_headroom_scales_with_volume_size():
+ """Big volumes reserve proportionally; small ones keep a modest floor."""
+ assert _repair_backup_headroom_bytes(1_000_000_000) == _REPAIR_BACKUP_MIN_FREE_BYTES
+ assert _repair_backup_headroom_bytes(1_000_000_000_000) > _REPAIR_BACKUP_MIN_FREE_BYTES
+
+
+def test_disk_guard_accounts_for_sidecars(tmp_path):
+ """The copy includes -wal/-shm, so the space check must count them."""
+ db = _damaged_db(tmp_path, size=1_000_000)
+ db.with_name(db.name + "-wal").write_bytes(os.urandom(400_000_000))
+ usage = type(
+ "Usage",
+ (),
+ {"total": 10_000_000_000, "used": 0, "free": _REPAIR_BACKUP_MIN_FREE_BYTES + 300_000_000},
+ )()
+ with patch("shutil.disk_usage", return_value=usage):
+ path, reason = _backup_db_file(db)
+ assert path is None, "sidecar bytes were ignored by the free-space check"
+ assert reason is not None
+
+
+def test_failed_copy_leaves_no_countable_debris(tmp_path):
+ """Prune only runs on success, so a failed copy must self-clean.
+
+ Otherwise partials matching the backup prefix accumulate unbounded and,
+ on a later successful pass, are KEPT (newest by name) while intact
+ forensic copies get pruned away.
+ """
+ db = _damaged_db(tmp_path, size=1_000_000)
+ db.with_name(db.name + "-wal").write_bytes(os.urandom(1_000_000))
+ roomy = type(
+ "Usage", (), {"total": 500_000_000_000, "used": 0, "free": 400_000_000_000}
+ )()
+ real_copy2 = shutil.copy2
+
+ def sidecar_fails(src, dst, *a, **kw):
+ if str(src).endswith("-wal"):
+ Path(dst).write_bytes(b"PARTIAL" * 100)
+ raise OSError(28, "No space left on device")
+ return real_copy2(src, dst, *a, **kw)
+
+ with patch("shutil.disk_usage", return_value=roomy), \
+ patch("shutil.copy2", sidecar_fails):
+ for _ in range(6):
+ _backup_db_file(db)
+ time.sleep(0.01)
+ os.utime(db, None)
+
+ assert len(_existing_malformed_backups(db)) <= _MAX_MALFORMED_BACKUPS
+
+ # a later successful pass must sweep any staging debris
+ with patch("shutil.disk_usage", return_value=roomy):
+ path, reason = _backup_db_file(db)
+ assert reason is None and path is not None
+ strays = list(tmp_path.glob("*.incomplete*"))
+ assert not strays, f"staging debris survived: {strays}"
+
+
def test_backup_allowed_with_ample_disk(tmp_path):
db = _damaged_db(tmp_path)
roomy = type(