From 7c1d0e16107df2b22408737d1258ee1be3c58e04 Mon Sep 17 00:00:00 2001 From: AMATH <116212274+amathxbt@users.noreply.github.com> Date: Sat, 9 May 2026 01:50:11 +0100 Subject: [PATCH] fix: _check_disk_usage_warning runs full rglob on every terminal call --- tools/terminal_tool.py | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index b65af93fa3bb..193a6cdd6046 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -181,8 +181,24 @@ def _check_vercel_sandbox_requirements(config: dict[str, Any]) -> bool: return False +# Cache for disk usage warning to avoid full rglob scan on every call. +# The check is advisory-only — staleness for up to 5 minutes is acceptable. +_disk_usage_cache: dict = {"timestamp": 0.0, "result": False} +_DISK_USAGE_CACHE_TTL = 300.0 # seconds + + def _check_disk_usage_warning(): - """Check if total disk usage exceeds warning threshold.""" + """Check if total disk usage exceeds warning threshold. + + Result is cached for :data:`_DISK_USAGE_CACHE_TTL` seconds (default: + 5 minutes) to avoid an expensive recursive filesystem scan on every + terminal command. The check is advisory-only so a stale result is + harmless. + """ + import time as _time_mod + now = _time_mod.monotonic() + if now - _disk_usage_cache["timestamp"] < _DISK_USAGE_CACHE_TTL: + return _disk_usage_cache["result"] try: scratch_dir = _get_scratch_dir() @@ -199,14 +215,16 @@ def _check_disk_usage_warning(): total_gb = total_bytes / (1024 ** 3) - if total_gb > DISK_USAGE_WARNING_THRESHOLD_GB: + exceeded = total_gb > DISK_USAGE_WARNING_THRESHOLD_GB + if exceeded: logger.warning("Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().", total_gb, DISK_USAGE_WARNING_THRESHOLD_GB) - return True - - return False + _disk_usage_cache["timestamp"] = _time_mod.monotonic() + _disk_usage_cache["result"] = exceeded + return exceeded except Exception as e: logger.debug("Disk usage warning check failed: %s", e, exc_info=True) + # Don't update cache on error so the next call retries. return False