Disk Space Analysis and Cleanup with LLMs: A Practical Guide

    This article explains how to use an LLM-driven approach to build a disk space analysis and cleanup tool. It covers why full disks cause cascading failures, how to turn a natural-language prompt into an executable specification, key code review points such as path validation and safe deletion, engineering practices for previewable and auditable cleanup, and long-term capacity governance through scheduled scans and threshold alerts. A best-practice checklist is included.

    1. Why Full Disks Are a Frequent Failure

    In day-to-day development and operations, running out of disk space is both common and far-reaching. It rarely happens all at once. Instead, it builds up from continuously written logs, accumulated temporary files, growing package caches, and build artifacts that are never cleaned. As usage approaches 100%, a chain of failures follows: database writes fail, service processes exit unexpectedly, logs cannot be flushed to disk, and containers fail to start.

    The traditional response is manual, layer-by-layer investigation: check overall partition usage, drill down directory by directory to find large files, and then decide what is safe to delete. This process depends heavily on experience and carries a real risk of deleting critical data. With an AI coding assistant, you can describe the requirement in one natural-language sentence and quickly generate a small “disk analysis + cleanup” program, handing repetitive work over to code.

    2. Requirement Breakdown: From One Prompt to an Executable Spec

    High-quality generated code starts with a clear abstraction of the requirement. The original request breaks down into four core capabilities:

    1. Space overview: Report total capacity, used, available, and utilization for each partition or a specified root directory.
    2. Drill-down analysis: Recursively measure size by directory level and output the paths with the highest usage.
    3. Large file detection: Within a given depth, filter files above a threshold and support grouping by extension.
    4. Safe cleanup: Delete only clearly regenerable directories, such as caches, temporary files, and old logs, with a dry run as the default.

    Writing the requirement as a structured prompt significantly improves the usability of the generated code, for example:

    1. Generate a command-line disk analysis and cleanup tool with the following requirements:
    2. 1. Support a specified root directory and recursion depth;
    3. 2. Output per-first-level-directory usage sorted by size, with utilization;
    4. 3. List the Top N files exceeding a size threshold;
    5. 4. Limit cleanup targets to cache and temporary directories; default to dry-run and require explicit confirmation to execute;
    6. 5. Skip paths without permission and record them in a log.

    3. Code Review Checklist for Generated Output

    LLM-generated code can cover most of the skeleton logic, but the following areas must be reviewed manually to avoid code that “runs but is dangerous.”

    • Path construction safety: All user-supplied paths must be normalized and boundary-checked; escaping the allowed root directory must be prohibited.
    • Deletion confirmation: By default, only print the deletion candidate list; real deletion requires a second confirmation or an explicit flag.
    • Symlink handling: Avoid following symlinks during traversal to prevent double counting or deleting link targets.
    • Permission and exception fallback: Catch exceptions for inaccessible directories and continue, then print a summary instead of crashing.
    • Performance strategy: Use streaming aggregation for large directory trees to avoid loading the entire file list into memory at once.

    A typical core routine for aggregation and filtering:

    1. import os
    2. def scan(root, max_depth=2, threshold_mb=500):
    3. big_files, dir_size = [], {}
    4. root = os.path.abspath(root)
    5. for cur, dirs, files in os.walk(root, followlinks=False):
    6. depth = cur[len(root):].count(os.sep)
    7. if depth >= max_depth:
    8. dirs[:] = []
    9. size = 0
    10. for f in files:
    11. p = os.path.join(cur, f)
    12. try:
    13. s = os.path.getsize(p)
    14. except OSError:
    15. continue
    16. size += s
    17. if s > threshold_mb * 1024 * 1024:
    18. big_files.append((s, p))
    19. dir_size[cur] = dir_size.get(cur, 0) + size
    20. top_dirs = sorted(dir_size.items(), key=lambda x: x[1], reverse=True)[:10]
    21. return top_dirs, sorted(big_files, reverse=True)[:20]

    4. Engineering Safe Cleanup

    Cleanup must rest on three principles: previewable, rollback-capable, and auditable. The recommended approach is to maintain a whitelist of cleanup-eligible directory rules, such as package manager caches, build intermediates, expired logs, and system temporary directories. All other paths are excluded from the deletion candidate set.

    1. Cleanup flow:
    2. 1. Generate the candidate list and estimated reclaimable space;
    3. 2. Output a human-readable report (path, size, last modified time);
    4. 3. Execute after manual or policy-based confirmation;
    5. 4. Record an operation log with time, path, size, and result.

    Protection thresholds should also be set: when the root partition usage exceeds a warning line, only analysis is allowed and automatic cleanup is disabled; paths containing database files, mount points, or configuration directories are excluded outright.

    5. From a One-Off Script to Ongoing Governance

    A one-time cleanup only relieves immediate pressure. Long-term stability requires turning the capability into a standing mechanism:

    • Scheduled inspection: Use scheduled jobs to periodically generate space reports and build usage trends.
    • Threshold alerts: Integrate with monitoring and alerting to notify the responsible owner when usage crosses a set watermark.
    • Log rotation: Configure size and retention count limits for logs to prevent unbounded growth.
    • Capacity planning: Estimate remaining days based on growth rate to expand or archive ahead of time.
    • Cloud coordination: Cold data can be moved down to object storage, keeping only hot data and indexes locally.

    To further reduce resource overhead, the analysis task can run in a container with only a read-only mount and a dedicated cache directory, applying least privilege.

    6. A Rational View of Model Efficiency and Stability

    In practice, developers care about both generation quality and response speed. Different models take different approaches to “reasoning length”: an overly long reasoning chain slows delivery, while well-calibrated reasoning improves the first-pass success rate. For coding tasks, focus on three things: whether the prompt states constraints clearly, whether the generated result has been reviewed and tested, and whether the runtime environment is stable.

    Network fluctuations, API rate limiting, and concurrency quotas can all affect the interactive coding experience. Engineering countermeasures include固化 reusable logic into local scripts and templates, keeping manual confirmation for critical operations, and handling sensitive data locally or on an intranet to reduce hard dependence on external services. If cloud resources are used, a closed loop can be built on common capabilities such as container platforms, log services, and monitoring and alerting; general product categories from Baidu AI Cloud can also serve as the foundation for such an architecture.

    7. Best-Practice Checklist

    1. State inputs, outputs, boundaries, and safety constraints explicitly in the prompt.
    2. Review generated code for path validation and a deletion whitelist.
    3. Default to dry-run: produce the report first, then execute.
    4. Do not follow symlinks during traversal; skip and summarize exception paths.
    5. Log cleanup actions for auditing and retrospective review.
    6. Replace manual firefighting with scheduled inspection and threshold alerts.
    7. Tier hot and cold data, archiving to object storage when necessary.
    8. Handle sensitive data locally or on an intranet first.

    8. Conclusion

    The value of “generating a disk analysis and cleanup tool from one sentence” is not to replace operations experience, but to automate repetitive locating and aggregation work so people can focus on strategy and risk judgment. As long as you hold to engineering principles of safety first, previewability, and auditability, and pair them with routine inspection and capacity planning, disk space problems shift from reactive firefighting to proactive governance, and system stability and maintainability improve accordingly.