:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(hogli): bound flox log dir by size, not just age (#72236)
Ben White58e90e7a1a68
diff --git a/.flox/env/on-activate.sh b/.flox/env/on-activate.shindex 9243209bf5ed..f40e8ee15c4b 100755--- a/.flox/env/on-activate.sh+++ b/.flox/env/on-activate.sh@@ -501,7 +501,8 @@ ${C_DIM} ${C_BOLD}q${C_RESET}${C_DIM} / ${C_BOLD}r${C_RESET}${C_DIM} in phrocs$fi# ── Silent background cleanup ──────────────────────────────────────-# Clean old flox log files (>7 days). Fire-and-forget after activation.+# Trim flox logs: drop >7-day-old files and cap total size (see doctor:disk).+# Fire-and-forget after activation. The find fallback (no venv) is age-only.(if [[ -x "$UV_PROJECT_ENVIRONMENT/bin/python" && -f "$FLOX_ENV_PROJECT/bin/hogli" ]]; thenPOSTHOG_TELEMETRY_OPT_OUT=1 "$UV_PROJECT_ENVIRONMENT/bin/python" \diff --git a/tools/hogli-commands/hogli_commands/doctor.py b/tools/hogli-commands/hogli_commands/doctor.pyindex 0dffec3d197c..c1bbad44f785 100644--- a/tools/hogli-commands/hogli_commands/doctor.py+++ b/tools/hogli-commands/hogli_commands/doctor.py@@ -25,6 +25,15 @@ from hogli.manifest import REPO_ROOT, get_manifestfrom . import hintsMAX_SAMPLE_PATHS = 8++# Flox writes a fresh log per shell activation, and direnv re-activates on every+# `cd` into the tree (plus every agent/non-interactive shell), so the log dir can+# reach tens of GB well inside any age window. We bound it two ways: drop anything+# older than the age cutoff, then trim the oldest survivors past a total-size+# budget so churn alone can't balloon the directory.+FLOX_LOG_MAX_AGE_DAYS = 7+FLOX_LOG_MAX_TOTAL_BYTES = 512 * 1024 * 1024 # 512 MiB of recent logs is plenty for debugging+PYTHON_CACHE_PATTERNS = ("__pycache__", ".mypy_cache", ".pytest_cache", ".ruff_cache")NODE_ARTIFACT_PATTERNS = (".parcel-cache",@@ -156,13 +165,17 @@ def doctor_disk(id="flox_logs",title="📁 Flox logs (.flox/log)",description=[- "Remove Flox CLI logs older than 7 days from the dev environment manager.",- "These logs can grow to 32GB+ after repeated 'flox' operations.",+ f"Remove Flox CLI logs older than {FLOX_LOG_MAX_AGE_DAYS} days, then trim the",+ f"remainder past {_format_size(FLOX_LOG_MAX_TOTAL_BYTES)} (oldest first).",+ "Every shell activation writes a log, so these grow to tens of GB otherwise.",],estimate=_estimate_flox_logs,- cleanup=_cleanup_flox_logs,- confirmation_prompt="Clean up Flox logs older than 7 days?",- dry_run_message="Would run: find .flox/log -name '*.log' -mtime +7 -delete",+ cleanup=_cleanup_items,+ confirmation_prompt="Clean up old and oversized Flox logs?",+ dry_run_message=(+ f"Would remove Flox logs older than {FLOX_LOG_MAX_AGE_DAYS} days "+ f"and trim the rest past {_format_size(FLOX_LOG_MAX_TOTAL_BYTES)}"+ ),),CleanupCategory(id="docker",@@ -367,7 +380,11 @@ def _run_category(def _estimate_flox_logs(repo_root: Path) -> CleanupEstimate:- """Check Flox log directory - cleanup happens via find command."""+ """Select Flox logs to remove: everything past the age cutoff, plus the+ oldest survivors past the total-size budget.++ The returned items are deleted by the generic ``_cleanup_items`` handler.+ """flox_log_dir = repo_root / ".flox" / "log"if not flox_log_dir.exists():@@ -377,16 +394,58 @@ def _estimate_flox_logs(repo_root: Path) -> CleanupEstimate:items=[],)- # Just check if directory exists and has logs - don't calculate sizes- # Cleanup is done via find command for simplicity- log_count = len(list(flox_log_dir.glob("*.log")))+ logs: list[tuple[Path, int, float]] = [] # (path, size, mtime)+ for log in flox_log_dir.rglob("*.log"):+ try:+ stat = log.stat()+ except (FileNotFoundError, PermissionError, OSError):+ continue+ if not log.is_file():+ continue+ logs.append((log, stat.st_size, stat.st_mtime))++ if not logs:+ return CleanupEstimate(total_size=0.0, items=[], details=[" No Flox log files found."])++ doomed, retained_size = _select_flox_logs_to_remove(logs)details = [- " Runs: find .flox/log -name '*.log' -mtime +7 -delete",- f" Found {log_count} log file(s) in directory.",+ f" Removes logs older than {FLOX_LOG_MAX_AGE_DAYS} days, then trims the rest "+ f"past {_format_size(FLOX_LOG_MAX_TOTAL_BYTES)}.",+ f" Found {len(logs)} log file(s); {len(doomed)} to remove, keeping {_format_size(retained_size)}.",]+ if doomed:+ details.extend(_describe_items(doomed, repo_root, " Sample files:"))- return CleanupEstimate(total_size=0.0, items=[], details=details)+ total = sum(item.size for item in doomed)+ return CleanupEstimate(total_size=total, items=doomed, details=details)+++def _select_flox_logs_to_remove(logs: Sequence[tuple[Path, int, float]]) -> tuple[list[CleanupItem], float]:+ """Return the logs to delete and the retained size, applying age then budget.++ Deletes anything older than the age cutoff, then — oldest first — trims the+ survivors until the retained set fits within the size budget.+ """++ cutoff = time.time() - (FLOX_LOG_MAX_AGE_DAYS * 24 * 60 * 60)+ doomed: list[CleanupItem] = []+ survivors: list[tuple[Path, int, float]] = []+ for path, size, mtime in logs:+ if mtime < cutoff:+ doomed.append(CleanupItem(path, size, is_dir=False))+ else:+ survivors.append((path, size, mtime))++ survivors.sort(key=lambda entry: entry[2]) # oldest first+ retained_size = float(sum(size for _, size, _ in survivors))+ for path, size, _ in survivors:+ if retained_size <= FLOX_LOG_MAX_TOTAL_BYTES:+ break+ doomed.append(CleanupItem(path, size, is_dir=False))+ retained_size -= size++ return doomed, retained_sizedef _estimate_python_caches(repo_root: Path) -> CleanupEstimate:@@ -586,24 +645,6 @@ def _cleanup_items(estimate: CleanupEstimate, _: Path) -> CleanupStats:return CleanupStats(freed=freed, deleted_anything=freed > 0)-def _cleanup_flox_logs(_: CleanupEstimate, repo_root: Path) -> CleanupStats:- """Execute find command to clean up old Flox logs."""-- flox_log_dir = repo_root / ".flox" / "log"- if not flox_log_dir.exists():- return CleanupStats(deleted_anything=False)-- result = subprocess.run(- ["find", str(flox_log_dir), "-name", "*.log", "-type", "f", "-mtime", "+7", "-delete"],- capture_output=True,- check=False,- )- if result.returncode == 0:- return CleanupStats(deleted_anything=True)-- return CleanupStats(deleted_anything=False)--def _cleanup_git(_: CleanupEstimate, repo_root: Path) -> CleanupStats:"""Execute git cleanup: prune remotes, expire reflogs, and run gc."""diff --git a/tools/hogli-commands/hogli_commands/tests/test_doctor.py b/tools/hogli-commands/hogli_commands/tests/test_doctor.pyindex ba99e701c768..127f2e4d0bcb 100644--- a/tools/hogli-commands/hogli_commands/tests/test_doctor.py+++ b/tools/hogli-commands/hogli_commands/tests/test_doctor.py@@ -1,4 +1,5 @@import os+import timeimport hashlibfrom pathlib import Pathfrom types import SimpleNamespace@@ -6,6 +7,8 @@ from types import SimpleNamespaceimport pytestfrom hogli_commands.doctor import (+ FLOX_LOG_MAX_AGE_DAYS,+ FLOX_LOG_MAX_TOTAL_BYTES,_binary_arches,_collect_import_targets,_config_procs,@@ -18,9 +21,52 @@ from hogli_commands.doctor import (_phrocs_runtime_pairs,_phrocs_socket_path,_probe_command_imports,+ _select_flox_logs_to_remove,_tail,)+_QUARTER_BUDGET = FLOX_LOG_MAX_TOTAL_BYTES // 4+_TWO_FIFTHS_BUDGET = int(FLOX_LOG_MAX_TOTAL_BYTES * 0.4)+++ "specs, expected_doomed, expected_retained",+ [+ pytest.param(+ [("old.log", 1, FLOX_LOG_MAX_AGE_DAYS + 1), ("recent.log", FLOX_LOG_MAX_TOTAL_BYTES // 2, 0)],+ ["old.log"],+ float(FLOX_LOG_MAX_TOTAL_BYTES // 2),+ id="age-cutoff-removes-old-keeps-large-recent",+ ),+ pytest.param(+ [+ ("newest.log", _TWO_FIFTHS_BUDGET, 1),+ ("middle.log", _TWO_FIFTHS_BUDGET, 2),+ ("oldest.log", _TWO_FIFTHS_BUDGET, 3),+ ],+ ["oldest.log"],+ float(2 * _TWO_FIFTHS_BUDGET),+ id="budget-trims-oldest-survivor-first",+ ),+ pytest.param(+ [("a.log", _QUARTER_BUDGET, 1), ("b.log", _QUARTER_BUDGET, 2)],+ [],+ float(2 * _QUARTER_BUDGET),+ id="within-age-and-budget-keeps-all",+ ),+ ],+)+def test_select_flox_logs_to_remove(+ specs: list[tuple[str, int, int]],+ expected_doomed: list[str],+ expected_retained: float,+) -> None:+ now = time.time()+ logs = [(Path(name), size, now - age_days * 86400) for name, size, age_days in specs]+ doomed, retained = _select_flox_logs_to_remove(logs)+ assert sorted(item.path.name for item in doomed) == sorted(expected_doomed)+ assert retained == expected_retained+@pytest.mark.parametrize("args",