from __future__ import annotations import gzip import os import shutil from dataclasses import dataclass, asdict from datetime import UTC, datetime from pathlib import Path from typing import Dict, Iterable, List import pandas as pd @dataclass class DiskSnapshot: timestamp_utc: str stage: str note: str free_gb: float repo_size_gb: float projected_output_gb: float projected_free_after_gb: float @dataclass class DiskCleanupAction: timestamp_utc: str action: str target: str size_before_mb: float size_after_mb: float reclaimed_mb: float status: str reason: str def _utc_now() -> str: return datetime.now(UTC).isoformat() def _is_within_repo(target: Path, repo_root: Path) -> bool: try: target.resolve().relative_to(repo_root.resolve()) return True except Exception: return False def directory_size_bytes(path: Path) -> int: total = 0 if not path.exists(): return total for entry in path.rglob("*"): if entry.is_file(): try: total += entry.stat().st_size except OSError: continue return total def system_free_bytes(path: Path) -> int: return int(shutil.disk_usage(path).free) def snapshot_disk_state(repo_root: Path, stage: str, note: str, projected_output_gb: float = 0.0) -> DiskSnapshot: free = system_free_bytes(repo_root) repo_size = directory_size_bytes(repo_root) projected_after = max(0.0, (free / (1024**3)) - float(projected_output_gb)) return DiskSnapshot( timestamp_utc=_utc_now(), stage=stage, note=note, free_gb=free / (1024**3), repo_size_gb=repo_size / (1024**3), projected_output_gb=float(projected_output_gb), projected_free_after_gb=projected_after, ) def append_disk_snapshot(csv_path: Path, snapshot: DiskSnapshot) -> None: csv_path.parent.mkdir(parents=True, exist_ok=True) row = pd.DataFrame([asdict(snapshot)]) if csv_path.exists(): old = pd.read_csv(csv_path) out = pd.concat([old, row], ignore_index=True) else: out = row out.to_csv(csv_path, index=False) def requires_cleanup(snapshot: DiskSnapshot, *, min_free_gb: float = 8.0) -> bool: return bool(snapshot.projected_free_after_gb < float(min_free_gb)) def _compress_file(path: Path) -> tuple[float, float]: before = path.stat().st_size / (1024**2) gz_path = path.with_suffix(path.suffix + ".gz") with path.open("rb") as src, gzip.open(gz_path, "wb", compresslevel=6) as dst: shutil.copyfileobj(src, dst) path.unlink(missing_ok=True) after = gz_path.stat().st_size / (1024**2) return before, after def _prune_batches(raw_root: Path, keep_first_n: int) -> tuple[float, float]: before = directory_size_bytes(raw_root) / (1024**2) batches = sorted([p for p in raw_root.iterdir() if p.is_dir()]) for batch in batches[keep_first_n:]: shutil.rmtree(batch, ignore_errors=True) after = directory_size_bytes(raw_root) / (1024**2) return before, after def run_repository_local_cleanup( repo_root: Path, *, results_dir: Path, keep_raw_batches: int = 6, ) -> List[DiskCleanupAction]: actions: List[DiskCleanupAction] = [] def record(action: str, target: Path, before: float, after: float, status: str, reason: str) -> None: actions.append( DiskCleanupAction( timestamp_utc=_utc_now(), action=action, target=str(target), size_before_mb=float(before), size_after_mb=float(after), reclaimed_mb=max(0.0, float(before - after)), status=status, reason=reason, ) ) # 1) Remove replay caches after summary tables are present. for replay in results_dir.glob("*/replay_cache"): parent = replay.parent if not _is_within_repo(replay, repo_root): record("remove_dir", replay, 0.0, 0.0, "skipped", "outside_repo_guard") continue if not (parent / "summary.json").exists(): record("remove_dir", replay, 0.0, 0.0, "skipped", "missing_summary") continue before = directory_size_bytes(replay) / (1024**2) shutil.rmtree(replay, ignore_errors=True) after = directory_size_bytes(replay) / (1024**2) if replay.exists() else 0.0 record("remove_dir", replay, before, after, "ok", "replay_cache_not_required_for_final_reports") # 2) Prune oversized raw output batches but keep representative subset. for raw_root in list(results_dir.glob("*/raw_rdock_outputs")) + list(results_dir.glob("*/predock/raw_rdock_outputs")): if not raw_root.exists() or not raw_root.is_dir(): continue if not _is_within_repo(raw_root, repo_root): record("prune_batches", raw_root, 0.0, 0.0, "skipped", "outside_repo_guard") continue before, after = _prune_batches(raw_root, keep_first_n=keep_raw_batches) record("prune_batches", raw_root, before, after, "ok", "keep_representative_raw_batches_only") # 3) Compress large logs. for log_file in results_dir.rglob("*.log"): if not log_file.exists() or not log_file.is_file(): continue if not _is_within_repo(log_file, repo_root): record("compress_log", log_file, 0.0, 0.0, "skipped", "outside_repo_guard") continue if log_file.stat().st_size < 2 * 1024 * 1024: continue before, after = _compress_file(log_file) record("compress_log", log_file, before, after, "ok", "large_log_compression") # 4) Remove stale duplicate work dirs if summaries exist. for work_dir in results_dir.glob("*/work"): parent = work_dir.parent if not (parent / "summary.json").exists(): continue if not _is_within_repo(work_dir, repo_root): record("remove_work_dir", work_dir, 0.0, 0.0, "skipped", "outside_repo_guard") continue before = directory_size_bytes(work_dir) / (1024**2) shutil.rmtree(work_dir, ignore_errors=True) record("remove_work_dir", work_dir, before, 0.0, "ok", "parsed_outputs_already_persisted") return actions def write_cleanup_actions(path: Path, actions: Iterable[DiskCleanupAction]) -> None: lines = ["# Disk Cleanup Actions", ""] actions = list(actions) if not actions: lines.append("- No cleanup actions executed.") else: for a in actions: lines.append( f"- [{a.timestamp_utc}] action={a.action} target=`{a.target}` status={a.status} " f"reclaimed_mb={a.reclaimed_mb:.2f} reason={a.reason}" ) path.parent.mkdir(parents=True, exist_ok=True) path.write_text("\n".join(lines), encoding="utf-8") def write_disk_guard_report( path: Path, snapshots: Iterable[DiskSnapshot], actions: Iterable[DiskCleanupAction], *, min_free_gb: float, ) -> None: snaps = list(snapshots) acts = list(actions) lines = [ "# Disk Guard Report", "", f"- Min free threshold (GB): `{min_free_gb}`", f"- Snapshots captured: `{len(snaps)}`", f"- Cleanup actions: `{len(acts)}`", "", "## Snapshot Timeline", ] for s in snaps: lines.append( f"- [{s.timestamp_utc}] stage={s.stage} free_gb={s.free_gb:.2f} repo_size_gb={s.repo_size_gb:.2f} " f"projected_output_gb={s.projected_output_gb:.2f} projected_free_after_gb={s.projected_free_after_gb:.2f} note={s.note}" ) lines.extend(["", "## Cleanup Summary"]) reclaimed = sum(a.reclaimed_mb for a in acts if a.status == "ok") lines.append(f"- Total reclaimed MB: `{reclaimed:.2f}`") outside_repo_violations = [a for a in acts if a.reason == "outside_repo_guard" and a.status == "ok"] lines.append(f"- Outside-repo destructive actions: `{len(outside_repo_violations)}`") path.parent.mkdir(parents=True, exist_ok=True) path.write_text("\n".join(lines), encoding="utf-8")